1. 程式人生 > 實用技巧 >基本資料型別及內建方法

基本資料型別及內建方法

目錄

一整形int

基本使用========
2 定義方式
age = 18
int功能可以把純數字的字串轉成int型別

res = int("18")
res= int("1.8")
print(type(res))

瞭解

print(bin(11))二進位制
print(oct(11))八進位制
print(hex(11))十六進位制

3,常用操作加內建方法
算數運算子與比較運算
二:浮點型float
該型別總結

===

3,常用操作加內建方法
算數運算子與比較運算

二:浮點型float

該型別總結===

1,用途:薪資丶身高 體重
2,定義方式
salary = 3.1
float功能可以吧浮點陣列成的字串轉成float型別

res = float("1.8")
print(type(res))

3,常用操作加內建方法
算數運算子與比較運算

=該型別總結====
存一個值
不可變

三 字串型別

基本使用
2,定義方式:在引號("",'',"""""")內包含一段字串
s = "helloo"
str功能可以把任意型別轉換成str型別\

res = str([1,2,3])
print(type(res))

3,常用操作加內建方法
==================>優先掌握的操作

1.按索引取值(正向取值加反向取值):只能取

s = "hello world"
print(s[0],type(s[0]))
print(s[-1])

s[1] = "E"  # 不能修改

非法操作
s[2222]
s[11] = "A"

2、切片(顧頭不顧尾,步長)=>屬於拷貝操作

s = "hello world"
new_s=s[1:7]
print(new_s)
print(s)

new_s=s[1:7:2]  #1 3 5
print(new_s)
print(s)

new_s=s[:7:2]
new_s=s[::2]  # 0 2 4 6 8 10
              h l o w r  d
print(new_s)

new_s=s[::]  # 完整拷貝字串,只留一個冒號就可以new_s=s[:]
print(new_s)

3、長度len

s = "hello world"
print(len(s))

res=print("sfd")
print(res)

4、成員運算in和not in

s = "hello world"

# print("hel" in s)

print("egon" not in s) # 語義明確,推薦使用

# print(not "egon" in s)

5、移除空白strip

s = " \n        hel lo  \t "
new_s = s.strip()
print(new_s)
print(s)  # 沒有改變原字串

應用案列:

name = input("your name>>> ").strip()  # name = "egon "
pwd = input("your pwd>>> ").strip()

if name == "egon" and pwd == "123":
    print('login successful')
else:
    print('user or password error')


去除左右兩邊的非空白字元
print("**+=-%^#****he**llo**%^#**+=**".strip("*+=-%^#"))

6、切分split:把字串按照某個分隔符切成一個列表

userinfo = "egon_dsb:123:18:3.1"
res = userinfo.split(":")

# print(res[0])

print(res)
print("-".join(res))

純字串組成的列表
l = ["aaaa", "bbb", "ccc"]

# res=l[0]+":"+l[1]+":"+l[2]

res = ":".join(l)
print(res, type(res))

7、迴圈

for i in "hello":
    print(i)

=======================>需要掌握的操作:

1、strip,lstrip,rstrip
print("***hello***".strip("*"))
print("***hello***".lstrip("*"))
print("***hello***".rstrip("*"))
2、lower,upper
msg = "AbCDEFGhigklmn"
res = msg.lower()
res = msg.upper()
print(res)

res=msg.swapcase()
print(res)
3、startswith,endswith
msg = "sb is lxx sb"
print(msg.startswith("sb"))
print(msg.endswith("b"))
print(msg.endswith("c"))
4、split,rsplit
userinfo="egon:123:18"

# print(userinfo.split(":"))

print(userinfo.split(":",1))
print(userinfo.rsplit(":",1))
5、format的三種玩法

5.1 %s的方式

name = "egon"
age = 18
res1="my name is %s my age is %s" % (name,age)
print(res1)

5.2 format的方式

name = "egon"
age = 18
res1="my name is {} my age is {}".format(name,age)
res1="{0}{0}{0}{1}".format(name,age)
res1="my name is {name} my age is {age}".format(age=18,name="egon")
print(res1)

5.3 f''

name = "egon"
age = 18
res1 = f"my name is {name} my age is {age}"
print(res1)


瞭解:f搭配{}可以執行字串中的程式碼
res=f'{len("hello")}'
print(res)

f'{print("hello")}'

f包含的字串可以放到多行
name = "egon"
age = 18
res1 = f"my name is {name} " \
       f"my age is {age}"

{}內不能有\以及#
print(f'my name is {{egon}}')

print('勝率是 %s%%' %70)

瞭解:https://zhuanlan.zhihu.com/p/110406030

6、replace
msg = "***egon hello***"
res=msg.replace('*','').replace(' ','')
res=msg.strip('*').replace(' ','')
print(res)
s="lxx hahah wocale lxx sb 666"

# res=s.replace('lxx','sb')

res=s.replace('lxx','sb',1)
print(res
print(s)
7、isdigit:判斷字串是否由純數字組成
print("adsf123".isdigit())
print("123".isdigit())
print("12.3".isdigit())

age = input('>>>: ') # age = "        18     "
if age.isdigit():
    age=int(age)
    if age > 18:
        print('猜大了')
    elif age < 18:
        print('猜小了')
    else:
        print('猜對了')
else:
    print('必須輸入數字,小垃圾')

瞭解操作:

1.find,rfind,index,rindex,count

1.1 find:從指定範圍內查詢子字串的起始索引,找得到則返回數字1,找不到則返回-1

msg='tony say hello'
msg.find('o',1,3) # 在索引為1和2(顧頭不顧尾)的字元中查詢字元o的索引
1
1.2 index:同find,但在找不到時會報錯

msg.index('e',2,4) # 報錯ValueError
1.3 rfind與rindex:略
1.4 count:統計字串在大字串中出現的次數

msg = "hello everyone"
msg.count('e') # 統計字串e出現的次數
4

msg.count('e',1,6) # 字串e在索引1~5範圍內出現的次數
1

2.center,ljust,rjust,zfill

name='tony'
name.center(30,'-') # 總寬度為30,字串居中顯示,不夠用-填充
-------------tony-------------

name.ljust(30,'') # 總寬度為30,字串左對齊顯示,不夠用填充
tony**************************

name.rjust(30,'') # 總寬度為30,字串右對齊顯示,不夠用填充
**************************tony

name.zfill(50) # 總寬度為50,字串右對齊顯示,不夠用0填充
0000000000000000000000000000000000000000000000tony

3.expandtabs

name = 'tony\thello' # \t表示製表符(tab鍵)
name
tony hello

name.expandtabs(1) # 修改\t製表符代表的空格數
tony hello

4.captalize,swapcase,title

4.1 captalize:首字母大寫

message = 'hello everyone nice to meet you!'
message.capitalize()
Hello everyone nice to meet you!
4.2 swapcase:大小寫翻轉

message1 = 'Hi girl, I want make friends with you!'
message1.swapcase()
hI GIRL, i WANT MAKE FRIENDS WITH YOU!
4.3 title:每個單詞的首字母大寫

msg = 'dear my friend i miss you very much'
msg.title()
Dear My Friend I Miss You Very Much

5.is數字系列

在python3中
num1 = b'4' #bytes
num2 = u'4' #unicode,python3中無需加u就是unicode
num3 = '四' #中文數字
num4 = 'Ⅳ' #羅馬數字

isdigt:bytes,unicode

num1.isdigit()
True

num2.isdigit()
True

num3.isdigit()
False

num4.isdigit()
False

isdecimal:uncicode(bytes型別無isdecimal方法)

num2.isdecimal()
True

num3.isdecimal()
False

num4.isdecimal()
False

isnumberic:unicode,中文數字,羅馬數字(bytes型別無isnumberic方法)

num2.isnumeric()
True

num3.isnumeric()
True

num4.isnumeric()
True

三者不能判斷浮點數

num5 = '4.3'
num5.isdigit()
False

num5.isdecimal()
False

num5.isnumeric()
False

'''
總結:
最常用的是isdigit,可以判斷bytes和unicode型別,這也是最常見的數字應用場景
如果要判斷中文數字或羅馬數字,則需要用到isnumeric。
'''

6.is其他

name = 'tony123'
name.isalnum() #字串中既可以包含數字也可以包含字母
True
name.isalpha() #字串中只包含字母
False
name.isidentifier()
True
name.islower() # 字串是否是純小寫
True
name.isupper() # 字串是否是純大寫
False
name.isspace() # 字串是否全是空格
False
name.istitle() # 字串中的單詞首字母是否都是大寫
False

=該型別總結==
存一個值
有序
不可變

四 列表

4.1定義:在[]號內用逗號分隔開多個任意型別的值

l1 = [111,222,"aaa",[55,66]] # 本質l1 = list([111,222,"aaa",[55,66]])

4.2型別轉換:但凡能夠被for迴圈遍歷的資料型別都可以傳給list()轉換成列表型別,

list()
if 會跟for迴圈一樣遍歷出資料型別中包含的每一個元素然後放到列表中:

list("aabbcc")
['a', 'a', 'b', 'b', 'c', 'c']
list([1, 2, 3])
[1, 2, 3]
list({"name": "liu", "age": 18})
['name', 'age']
list((1, 2, 3))
[1, 2, 3]
list({1, 2, 3, 4})
[1, 2, 3, 4]

4.3使用

4.3 優先掌握的操作

1.按索引位置存取值(正向存取,反向c存取):既可以存也可以取
正向取:(從左到右)
my_friends = ["tony","jason","tom",1,2]
my_friends[0] # tony

反向取(負號從右往左)
my_friends[-1] # 2

if對於list來說, 既可以按照索引取值, 又可以按照索引修改指定位置的值, 但是索引位置不存在則會報錯:
my_friends = ["tony","jason","tom",1,2]
my_friends[1] = "liu"
my_frieds[9] # 報錯
2.切片(顧頭不顧尾,步長)

2.1切片顧頭不顧尾:取出索引為0到3的元素

my_friends = ["tony","jason","tom",1,2]
my_friends[0:4]
['tony', 'jason', 'tom', 1]

2.2 步長:0:4:2,第三個引數2代表步長,會從0開始,每次累加一個2即可,所以會取出索引0、2的元素

2.2 步長:0:4:2,第三個引數2代表步長,會從0開始,每次累加一個2即可,所以會取出索引0、2的元素

my_friends[0:4:2]
['tony', 'tom']
3.長度
len(my_friends)
5
4.成員運算in和 not in
'tony' in my_friends
True
"tony" not in my_friends
False
"xxxx" not in my_friends
True
5.新增

5.1append()列表尾部追加元素

l1 = [11,22,33,44,55]
l1.append("a")
l1
[11, 22, 33, 44, 55, 'a']

5.2.extend()一次性在列表尾部新增多個元素

l1.extend(["aa","bb",99])
[11, 22, 33, 44, 55, 'a', 'aa', 'bb', 99]
l1.insert(22,111)

5.3.insert()在指定位置插入元素

5.3.insert()在指定位置插入元素

6.刪除:

del萬能刪除法

L= [11,22,33,44]
del l[0]
l
[22,33,44]

pop()預設刪除列表最後一個元素,並將刪除的值返回,括號內可以通過加索引值來指定刪除元素

l = [11,22,333,44]
res = l.pop()
res
44
res = l.pop()
res
333

remove()括號內指名道姓表示要刪除那個元素,沒有返回值

l = [11,22,33,44]
res = l.remove(22)
print(res)
None
7.reverse()顛倒列表內元素順序
l = [11,22,33,44]
l.reverse()
[44, 33, 22, 11]
8.sort()給列表內所有元素排序

排序是列表元素之間必須是相同的資料型別,不可混搭,不然報錯

l = [11,22,3,42,7,55]
l.sort()
l
[3, 7, 11, 22, 42, 55]  # 預設從小到大排序
l = [11,22,3,42,7,55]
l.sort(reverse=True)  # reverse用來指定是否跌倒排序,預設為False
l
[55, 42, 22, 11, 7, 3]

通過索引取值實現列表翻轉

l[::-1]
[55, 42, 22, 11, 7, 3]

瞭解知識:
我們常用的數字型別直接比較大小,但其實,字串、列表等都可以比較大小,原理相同:都是依次比較對應位置的元素的大小,如果分出大小,則無需比較下一個元素,比如

l1=[1,2,3]
l2=[2,]
l2 > l1
True

字元之間的大小取決於它們在ASCII表中的先後順序,越往後越大

字元之間的大小取決於它們在ASCII表中的先後順序,越往後越大

s1='abc'
s2='az'
s2 > s1 # s1與s2的第一個字元沒有分出勝負,但第二個字元'z'>'b',所以s2>s1成立
True

所以我們也可以對下面這個列表排序

所以我們也可以對下面這個列表排序

l = ['A','z','adjk','hello','hea']
l.sort()
l
['A', 'adjk', 'hea', 'hello','z']
9.迴圈

迴圈遍歷my_friends列表裡面的值

for line in my_friends:
    print(line)
'tony'
'jack'
'jason'
4
5

====該型別總結=
存多個值
有序
可變

五:元祖

5.1作用

元祖與列表類似,也是可以存多個任意型別的元素,不同之處是元祖的元素不可以改,
即元祖相當於不可變列表,用於記錄多個固定不允許修改的值,單純用於取.
元祖就是一個不可變的列表
用途:按照索引位置存放多個任意型別的值,索引反應的是位置/順序
定義方式:在()內用逗號分隔開多個任意型別的值/元素
t = (10)
print(type(t))
強調:當元祖內只有一個元素時,必必須加括號

t = (10,)
print(type(t))
t = (11,22,"aa",10.1,[11,22])
print(t[-1][0])
t[0] = 111 # 不能改
t[-1] = 333 # 不能改
t=(11,22,[33,44])
print(id(t[0]),id(t[1]),id(t[2]))

t[2][0]=333333333

# print(t)

print(id(t[0]),id(t[1]),id(t[2]))

t=(11,22)  # t=tuple(...)
print(type(t))

型別轉換

tuple(所有可以被for迴圈遍歷的型別)
t = ()
print(t)
print(type(t))


常用操作加內建方法
優先掌握的操作:

1.按照索引取值(正向取加反向取):只能取
t = (10,1.1,"aaa",[11,33])
print(t[0])
2.切片顧頭不顧尾
t = (11,22,33,44,55)
print(t[0:3])
3.len長度
t = (11,22,33,44,55)
print(len(t))
4.成員運算 in 和 not in
t = (11,22,33,44,55)
print(11 in t)

5 迴圈

for x in t:
   print(x)

====該型別總結=

存多個值
有序
不可變

六字典型別

1.用途:

按key:value的形式存放多個任意型別的value,key反應的是value的屬性

2.定義方式:

在{}內用逗號分給開多個key:value,其中value可以是任意型別
而key必須是不可變型別,通常是字串型別

d = {"k1":111,"k2":222,"k3":333} # key重複,只保留一個
print(d)

d = {1:"aaa",2.1:"bbb",[2,3]:"ccc"}
print(type(d))
print(d[()])

型別轉換

型別轉換

l = [("name","egon"),("age",18),["gender","male"]]

res = dict(l)
print(res)

d=dict(x=1,y=2,c=3)
print(d)

空字典

d = {}
print(type(d))

快速格式化字典
dic = {}.fromkeys(["name","age","gender"],None)
dic = {}.fromkeys("hello",None)
print(dic)
3.常用操作加內建方法

優先掌握的操作:

1.按key存取值:可存可取
d = {"k1":111}
print(d['k1'])
d['k2'] = 22
print(d)
2.長度 len()
d = {"k1":111,"k2":222}
print(len(d))
3.成員運算in和not in
d = {"k1":111,"k2":222}
print("k1"in d)
print(11 in d)
4、刪除

d={'k1':111,'k2':222}
萬能刪除,沒有返回值,代表的是單純的刪除

del d['k1']
print(d)

隨機刪,返回一個元組

res=d.popitem()
print(d)
print(res)

指定key刪除,有返回值,代表的是取走操作

res=d.pop('k1')
print(d)
print(res)
5.鍵keys(),值values(),鍵值對items()
d={'k1':111,'k2':222}
d.keys()
['k2', 'k1']
d.values()
[222, 111]
d.items()
[('k2', 222), ('k1', 111)]
6、迴圈
d={'k1':111,'k2':222}
for k in d:
    print(k)

for v in d.values():
    print(v)

for k,v in d.items():
    print(k,v)

keys=[]
for k in d:
    keys.append(k)

keys=list(d.keys())
print(keys)