# python3:符串常用操作 s1 = '字符串s1:信息。' s2 = '字符串s2' s3 = 1234 # 拼接字符串+ print('s1=',s1,'\ns2=',s2,'\ns3=',s3) print('拼接字符串(同類型)s1+s2:',s1+s2) print('拼接字符串(不同類型)s1+s2+str(s3):',s1+s2+str(s3)) #整數型的內容,需要str()轉換為字符串后再同其他字符串進行拼接 #字符串長度len() print('len(s1):',len(s1)) #字符串中字符的個數 print('len(s1.encode()):',len(s1.encode())) #utf-8編碼的字符串長度。1個漢字或中文標點:3個字節 print('len(s1.encode("gbk")):',len(s1.encode("gbk"))) #gbk編碼的字符串長度。1個漢字或中文標點:2個字節 print('len(s1.encode("gb2312")):',len(s1.encode("gb2312"))) #gb2312編碼的字符串長度。1個漢字或中文標點:2個字節 #截取字符串string[start:end:step] print('s1[:]:',s1[:]) #不填寫,默認從0到最后一個字符,step為1 print('s1[:5]:',s1[:5]) #從下標0到下標4,不包括下標5 print('s1[1:5]:',s1[1:5]) #從下標1到下標4,不包括下標5 print('s1[1:7:2]',s1[1:7:2]) #從下標1到下標7,不包括下標7,每2個 #截取的時候,如果索引不存在就會報錯,所以可以使用try……except try: print('s1[40]:',s1[40]) except IndexError: print("Oh,Maya,索引不存在哈~") #截取樣例 idcard = '110120199101010002' print('生日為:',idcard[6:10],'年',idcard[10:12],'月',idcard[12:14],'日') #生日為: 1991 年 01 月 01 日 print('生日為:',idcard[6:10]+'年'+idcard[10:12]+'月'+idcard[12:14]+'日') #生日為: 1991年01月01日 #分割字符串str.split(sep,maxsplit) ''' sep :默認為NONE,即所有的空字符(空格、換行'\n',制表符'\t'等) maxsplit:可選參數,指定分割次數,返回結果列表的的元素個數=maxsplit+1;不指定或者為-1,則分割次數沒有限制。 分割字符串把字符串分割為列表,而合並字符串是把列表合並為字符串。 ''' #樣例,輸出好友名稱 friends = '@小高 @小王 @小姜' friends1 = friends.split() print(friends) print('friends1 = friends.split()結果:',friends1) #['@小高', '@小王', '@小姜'] for friend in friends1: print('friends1 元素每個去掉@后:',friend[1:]) #去掉@輸出 #樣例,輸出好友名稱2 friends2 = '>@小高>小@王>>@小姜' print(friends2.split('>')) #['', '@小高', '@小王', '', '@小姜'] 注:當一個分隔符出現多個,就會每個分隔一次,沒有得到內容的,則產生一個空元素。 #合並字符串 snew=string.join(interable) ''' snew=string.join(interable),將多個字符串采用固定的分隔符連接在一起。 string :合並時的分隔符 interable:合並的對象,該對象中所有元素(字符串表示)將被合並為一個新的字符串。 ''' print('friends1:',friends1) print("'&'.join(friends1):",'&'.join(friends1)) #@小高&@小王&@小姜 #檢索字符串 count()方法 ''' str.count(sub,start,end) str:原字符串 sub:要檢索的字符串 start、end:檢索的范圍,可選參數 ''' dx = '@小高嗎 @小王 @小姜 @小尾巴呀' print('dx:',dx,'\ndx中含有@個數:',dx.count('@')) print('dx下標2~6中含有@個數:',dx.count('@',2,6)) #檢索字符串 find()方法:從左邊開始查找,rfind():從右邊開始查找。 ''' str.find(sub,start,end) str:原字符串 sub:要檢索的字符串 start、end:檢索的范圍,可選參數 ''' print('dx中首次出現@的索引:',dx.find('@')) #dx中首次出現@的索引: 0 print('dx下標2~6中首次出現@的索引:',dx.find('@',2,6)) #dx下標2~6中首次出現@的索引: 4 print('dx中首次出現*的索引(-1為不存在):',dx.find('*')) #dx中首次出現*的索引: -1 即不存在d print('dx中從右側首次出現@的索引:',dx.rfind('@')) #dx中從右側首次出現@的索引: 13 #檢索字符串 in print('dx中有@:','@' in dx) #dx中有@: True #檢索字符串index()方法,當指定字符串不存在時,會拋出異常 ''' str.index(sub,start,end) str :原字符串 sub :要檢索的字符串 start、end:檢索的范圍,可選參數 ''' print('dx中首次出現@的索引(index方法):',dx.index('@')) #dx中首次出現@的索引: 0 print('dx下標2~6中首次出現@的索引(index方法):',dx.index('@',2,6)) #dx下標2~6中首次出現@的索引: 4 #print('dx中首次出現*的索引:',dx.index('*')) #不存在會拋出異常:ValueError: substring not found #檢索字符串startswith()方法 ''' str.startswith(sub,start,end) str :原字符串 sub :要檢索的字符串 start、end:檢索的范圍,可選參數 ''' print('dx中開頭為@:',dx.startswith('@')) # True print('dx下標5~8開頭為@:',dx.startswith('@',5,8)) # True #檢索字符串endswith()方法 ''' str.endswith(sub,start,end) str :原字符串 sub :要檢索的字符串 start、end:檢索的范圍,可選參數 ''' print('dx中結尾為“呀”:',dx.endswith('呀')) # True print('dx下標1~3結尾為“嗎”:',dx.endswith('嗎',1,3)) # False 注:end是不含在內的 print('dx下標1~3結尾為“高”:',dx.endswith('高',1,3)) # True #大小寫 words = 'AbcdEf' print('AbcdEf的小寫們:',words.lower()) print('AbcdEf的大寫們:',words.upper()) #去除字符串中的空格和特殊字符 ''' strip()函數:去除左右兩邊空格和特殊字符 lstrip()函數:去除左邊空格和特殊字符 rstrip()函數:去除右邊空格和特殊字符 ''' a = ' @ 12 123\t4 5 @ ' print('a:'+a+'。') #a: @ 12 123 4 5 @ 。 print('a.strip():'+a.strip()+'。') #默認去掉左右兩側空的內容 a.strip():@ 12 123 4 5 @。 print('a.lstrip():'+a.lstrip()+'。') #默認去掉左側空的內容 a.lstrip():@ 12 123 4 5 @ 。 print('a.rstrip():'+a.rstrip()+'。') #默認去掉右側空的內容 a.rstrip(): @ 12 123 4 5 @。 a1 = '@12123@' print('a1:'+a1+'。') #print('a1.strip('@'):'+a1.strip('@')+'。') #去掉@的內容 注:引號中的和引號中的引號不要一樣,不然會報錯,他們會不知道誰是誰的另一半 print("a1.strip('@'):"+a1.strip('@')+'。') #去掉@的內容 a1.strip('@'):12123。 print("a1.rstrip('@'):"+a1.rstrip('@')+'。') #去掉@的內容 a1.rstrip('@'):@12123。 #格式化字符串 %[-][+][0][m][.n]格式化字符%exp ''' %+ :右對齊,正數前+,負數前- %- :左對齊,正數前無,負數前- %0 :左對齊,正數前無,負數前-,一般與m一起使用 %m :占有寬度,如占6位,%6 結果:000001 %.n:小數點后保留的位數 格式化字符:指定的類型,如: %s:字符串(str()顯示); %d:正數; %r:字符串(repr()顯示); %f:浮點數 %%:% ''' print('數字 %08d:\t字符串:%s' %(7,'啦啦啦啦啦')) #數字 00000007: 字符串:啦啦啦啦啦 print('數字 %+.2f:\t字符串:%s' %(7,'呀呀呀呀呀')) #數字 +7.00: 字符串:呀呀呀呀呀 #字符串格式化:.format()方法 '''<模板字符串>.format(<逗號分隔的參數>) 調用format()方法后會返回一個新的字符串,參數從0開始編號。 常用參數如下: {index:}:index:指定要設置格式的對象,在后面()中的參數的索引位置,索引從0開始,為空則按順序自動匹配,參數是否指定索引要一致,不可部分自動,部分手動,如:{:d}和{1:s}的模板是錯誤的。 {:fillword}:fillword:填充空白處的字符,如:{:0},指用0填充空白處。 {:<}:內容左對齊 {:>}:內容右對齊 {:=}:內容右對齊,填充內容放在左邊,僅對數字有效。如{:0=} ,內容右對齊,左邊用0填充 {:∧}:內容居中,配合width使用。 {:+}:正數前+,負數前- {:-}:正數前無,負數前- {: }:正數前 ,負數前-(空格) {:#}:各二進制、八進制和十六進制,顯示出對應的結果:0b,0o,0x,如{:#x},轉為十六進制的結果,並標記0x {:width}:指定所占的寬度,如:{:0=4}:內容共4位,右對齊,左邊用0填充 {:n}:指定保留的小數位數 {:type}:指定類型,如常用:{:s}字符串,{:f}浮點數,{:d}十進制整數,{:b}二進制整數,{:o}八進制整數,{:x}十六進制整數。 ''' ts1 = 7 ts2 = '我的幸運數字是七' ts3 = 79.768 moban2 = '編號:{:0=4d} \t自我介紹一下:{:s}\t這次考試分數{:=.2f}' print('moban2:',moban2.format(ts1,ts2,ts3)) #moban2: 編號:0007 自我介紹一下:我的幸運數字是七 這次考試分數79.77 ''' 注:一個模板中,如果出現多個占位符,其中一個需要手動指定參數的索引,那么所有的占位符均需手動指定參數索引,否則報錯: ValueError: cannot switch from automatic field numbering to manual field specification moban2應寫如下: ''' moban3 = '編號:{0:0>4d} \t自我介紹一下:{1:s}\t這次考試分數{2:=.2f}' print('moban3:',moban3.format(ts1,ts2,ts3)) #moban3: 編號:0007 自我介紹一下:我的幸運數字是七 這次考試分數79.77 ''' 注意: moban1 = "測試:{1:s}" print(moban1.format('我的幸運數字是七')) maya埋的坑~~~ 我以為所謂下標是指字符串的位置沒想到是指引用的對象在參數列表中的位置…… 參數列表中,參數列表中,參數列表中……【重要的事情說N遍!】 錯誤提示如下: IndexError: tuple index out of range 正確寫法如下: ''' moban1 = "測試:{1:s}" print(moban1.format('我的幸運數字是七','啥?哈哈,原來如此')) #測試:啥?哈哈,原來如此 #format()拓展 print('數字7的轉換:{1:0=4d}'.format('文字',7,'abc')) #數字7的轉換:0007 print('列表中的數字7的轉換:{0[1]:0=4d}'.format(['文字',7,'abc'])) #列表中的數字7的轉換:0007 參數為列表時,使用0[0],0[1],0[2]等標記參數位置。 print('元組中的數字7的轉換:{0[1]:0=4d}'.format(('文字',7,'abc'))) #元組中的數字7的轉換:0007 參數為元組時,使用0[0],0[1],0[2]等標記參數位置。 print('數字7的轉換<左對齊+:{1:0<+4d}'.format('文字',7,'abc')) #數字7的轉換<左對齊+:+700 print('數字7的轉換>左對齊+:{1:0>+4d}'.format('文字',7,'abc')) #數字7的轉換>左對齊+:00+7 print('數字-7的轉換>左對齊-:{1:0>-4d}'.format('文字',-7,'abc')) #數字-7的轉換>左對齊-:00-7 print('數字7的轉換>左對齊 :{1:0> 4d}'.format('文字',7,'abc')) #數字7的轉換>左對齊 :00 7 print('數字7居中:{:0^5d}'.format(7)) #數字7居中:00700 print('數字7小數顯示:{:.2f}'.format(7)) #數字7小數顯示:7.00 print('數字7浮點數顯示:{:f}'.format(7)) #數字7浮點數顯示:7.000000 print('數字777777金額顯示:{:,.4f}'.format(777777)) #數字777777金額顯示:777,777.0000 print('數字7百分比顯示:{:%}'.format(7)) #數字7百分比顯示:700.000000% print('數字-7居中:{:0^5d}'.format(-7)) #數字-7居中:0-700 print('數字-7居右:{:0=5d}'.format(-7)) #數字-7居右:-0007 print('數字-7二進制:{:#b}'.format(-7)) #數字-7二進制:-0b111 print('數字-7二進制:{:b}'.format(-7)) #數字-7二進制:-111 print('數字77八進制:{:o}'.format(77)) #數字77八進制:115 print('數字77八進制:{:#o}'.format(77)) #數字77八進制:0o115 print('數字77十六進制:{:x}'.format(77)) #數字77十六進制:4d print('數字77十六進制:{:#x}'.format(77)) #數字77十六進制:0x4d print('數字77科學計數法:{:e}'.format(77)) #數字77十六進制:4d print('數字0.01百分比(無小數):{:.0%}'.format(0.01)) #數字0.01百分比(無小數):1% #字符串編碼轉換encode()轉碼 bianma = '姜小八' bianma1 = bianma.encode(encoding='utf-8',errors='strict') bianma2 = bianma.encode('gbk') print(bianma,'轉為utf-8編碼:',bianma1) #姜小八 轉為utf-8編碼: b'\xe5\xa7\x9c\xe5\xb0\x8f\xe5\x85\xab' print(bianma,'轉為gbk編碼:',bianma2) #姜小八 轉為gbk編碼: b'\xbd\xaa\xd0\xa1\xb0\xcb' #字符串編碼轉換decode()方法解碼 print(bianma1,'utf-8解碼:',bianma1.decode(encoding='utf-8',errors='strict')) #b'\xe5\xa7\x9c\xe5\xb0\x8f\xe5\x85\xab' 解碼: 姜小八 print(bianma2,'GBK解碼:',bianma2.decode('GBK')) #b'\xbd\xaa\xd0\xa1\xb0\xcb' 解碼: 姜小八
結果:
C:\Users\yunniao\PycharmProjects\untitled1\venv\Scripts\python.exe D:/soft/Test/python-script/1030-zifuchuan.py
s1= 字符串s1:信息。
s2= 字符串s2
s3= 1234
拼接字符串(同類型)s1+s2: 字符串s1:信息。字符串s2
拼接字符串(不同類型)s1+s2+str(s3): 字符串s1:信息。字符串s21234
len(s1): 9
len(s1.encode()): 21
len(s1.encode("gbk")): 15
len(s1.encode("gb2312")): 15
s1[:]: 字符串s1:信息。
s1[:5]: 字符串s1
s1[1:5]: 符串s1
s1[1:7:2] 符s:
Oh,Maya,索引不存在哈~
生日為: 1991 年 01 月 01 日
生日為: 1991年01月01日
@小高 @小王 @小姜
friends1 = friends.split()結果: ['@小高', '@小王', '@小姜']
friends1 元素每個去掉@后: 小高
friends1 元素每個去掉@后: 小王
friends1 元素每個去掉@后: 小姜
['', '@小高', '小@王', '', '@小姜']
friends1: ['@小高', '@小王', '@小姜']
'&'.join(friends1): @小高&@小王&@小姜
dx: @小高嗎 @小王 @小姜 @小尾巴呀
dx中含有@個數: 4
dx下標2~6中含有@個數: 1
dx中首次出現@的索引: 0
dx下標2~6中首次出現@的索引: 5
dx中首次出現*的索引(-1為不存在): -1
dx中從右側首次出現@的索引: 13
dx中有@: True
dx中首次出現@的索引(index方法): 0
dx下標2~6中首次出現@的索引(index方法): 5
dx中開頭為@: True
dx下標5~8開頭為@: True
dx中結尾為“呀”: True
dx下標1~3結尾為“嗎”: False
dx下標1~3結尾為“高”: True
AbcdEf的小寫們: abcdef
AbcdEf的大寫們: ABCDEF
a: @ 12 123 4 5 @ 。
a.strip():@ 12 123 4 5 @。
a.lstrip():@ 12 123 4 5 @ 。
a.rstrip(): @ 12 123 4 5 @。
a1:@12123@。
a1.strip('@'):12123。
a1.rstrip('@'):@12123。
數字 00000007: 字符串:啦啦啦啦啦
數字 +7.00: 字符串:呀呀呀呀呀
moban2: 編號:0007 自我介紹一下:我的幸運數字是七 這次考試分數79.77
moban3: 編號:0007 自我介紹一下:我的幸運數字是七 這次考試分數79.77
測試:啥?哈哈,原來如此
數字7的轉換:0007
列表中的數字7的轉換:0007
元組中的數字7的轉換:0007
數字7的轉換<左對齊+:+700
數字7的轉換>左對齊+:00+7
數字-7的轉換>左對齊-:00-7
數字7的轉換>左對齊 :00 7
數字7居中:00700
數字7小數顯示:7.00
數字7浮點數顯示:7.000000
數字777777金額顯示:777,777.0000
數字7百分比顯示:700.000000%
數字-7居中:0-700
數字-7居右:-0007
數字-7二進制:-0b111
數字-7二進制:-111
數字77八進制:115
數字77八進制:0o115
數字77十六進制:4d
數字77十六進制:0x4d
數字77科學計數法:7.700000e+01
數字0.01百分比(無小數):1%
姜小八 轉為utf-8編碼: b'\xe5\xa7\x9c\xe5\xb0\x8f\xe5\x85\xab'
姜小八 轉為gbk編碼: b'\xbd\xaa\xd0\xa1\xb0\xcb'
b'\xe5\xa7\x9c\xe5\xb0\x8f\xe5\x85\xab' utf-8解碼: 姜小八
b'\xbd\xaa\xd0\xa1\xb0\xcb' GBK解碼: 姜小八
Process finished with exit code 0