Python入門教程之字串常用方法和格式化字串
Python中的字元串同樣適用標準的序列操作(索引,分片,乘法,成員判斷,求長度,取最小值和最大值),但因為字串是不可變的,因此字串不支援分片賦值。
1 s='http://www.baidu.com'
2 s[-3:]='aaa'
3 print(s)
輸出結果:
1 s[-3:]='aaa'
2 TypeError: 'str' object does not support item assignment
可以看出丟擲的錯誤資訊,字串不允許標記內部項。
但我們可以在字串中用一個百分比符號%s標記出一個佔位符,它表示我們將要在該位置插入轉換值的位置。s將會被格式化為字串,如果被轉換的物件不是字串,則會將其轉換為字串。
模板字串
除了用%s插入轉換值外,還可以使用substitute模板方法,用傳遞進來的關鍵字引數替換字串中的關鍵字。
1 from string import Template
2 s=Template('$x,glorious $b')
3 s=s.substitute(x='slurm',b='haha')
4 print(s)
輸出結果:
slurm,glorious haha
我們看到$s位置被替換為slurm,$b位置被替換為haha
如果被替換的位置是單詞的一部分,可以將其用{}括起來
1 from string import Template
2 s=Template('${x}glorious $b')
3 s=s.substitute(x='slurm',b='haha')
4 print
輸出結果:
slurmglorious haha
使用字典變數提供值得/名稱對替換
1 from string import Template
2 s=Template('$name come from $county ')
3 d={}
4 d['name']='zhangsan'5 d['county']='china'6 s=s.substitute(d)
7 print(s)
輸出結果:
zhangsancome fromchina
格式化輸出多個引數
1 s='%s come from %s'%('zhangsan','china')
2 print(s)
輸出結果:
1 zhangsan come from china
字串格式化轉換型別
轉換型別 | 解釋 |
d,i | 帶符號的十進位制整數 |
o | 不帶符號的八進位制 |
u | 不帶符號的十進位制 |
x | 不帶符號的十六進位制 |
e | 科學計數法表示的浮點數(小寫) |
E | 科學計數法表示浮點數(大寫) |
f.F | 十進位制浮點數 |
c | 單字元 |
r | 字串(用repr轉換任意Python物件) |
s | 字串(用str轉換任意python物件) |
字串與utf8互轉
1 s='你好'
2 print(s.encode('utf8'))
3 a=s.encode('utf8')
4 print(a.decode('utf8'))
輸出結果:
1 b'\xe4\xbd\xa0\xe5\xa5\xbd'
2 你好
字串的寬度和精度
寬度是指轉換後的值所保留的最小字元個數,精度則是結果中應該包含的小數位數
例如 輸出寬度為10的pi的值
1 from math import pi
2 p='%10f'%pi
3 for k, i in enumerate(p) : #使用enumerate函式列印序列
4 print('序列%s'%k,i)
1 序列0 2 序列1 3 序列2 3 4 序列3 . 5 序列4 1 6 序列5 4 7 序列6 1 8 序列7 5 9 序列8 910 序列9 3
列印精度為2的pi的值
1 from math import pi
2 p='%.2f'%pi
3 print(p)
輸出結果:
3.14
列印寬度為10,精度為2的pi的值
1 from math import pi
2 p='%10.2f'%pi
3 for k,i in enumerate(p):
4 print('序列%s 列印值%s'%(k,i))
列印結果:
1 序列0 列印值
2 序列1 列印值
3 序列2 列印值
4 序列3 列印值
5 序列4 列印值
6 序列5 列印值
7 序列6 列印值3
8 序列7 列印值.
9 序列8 列印值1
10 序列9 列印值4
我們看到,當整數部分沒有值時,將以空' ' 代替。
1 print('%+5d'%10)
2 print('%+5d'%-10)
輸出:
1 +10
2 -10
使用 '-'用來左對齊數值,用'+'表示不管是整數還是複數都會標識出符號
使用字串格式化,使我們的程式碼看著更簡潔
1 width=input('>>輸入寬度:')
2 price_with=10
3 item_width=int(width)-price_with
4 header_format='%-*s%*s'
5 format='%-*s%*.2f'
6 print('='*int(width))
7 print(header_format%(item_width,'item',price_with,'price'))
8 print('_'*int(width))
9 print(format%(item_width,'apple',price_with,0.4))
10 print(format%(item_width,'Pears',price_with,0.5))
輸出結果:
>>輸入寬度:30
==============================
item price
______________________________
apple 0.40
Pears 0.50
字串的常用方法:
方法名 | 解釋 | 案例 |
find | 在一個長的字串中查詢字串,返回字串所在位置的最左端的索引,如果沒有則返回-1 |
str='hello world' print(str.find('world')) 輸出:6 str='hello world' print(str.find('worldd')) 輸出:-1 |
join | 用來連線列表中的字串 |
l=['1','2','3','4','5','6'] sep='+' ret=sep.join(l) print(ret) 輸出: 1+2+3+4+5+6 |
lower | 返回字串的小寫母版(忽略使用者大小寫時使用,例如,使用者輸入使用者名稱含有大寫字母,輸入後將其轉換為小寫並與資料庫中的儲存字元匹配) |
str='HELLO WORLD' print(str.lower()) 輸出: hello world |
replace | 返回字串中所有被匹配項被替換後的所得到的新字串 |
str='HELLO WORLD' print(str.lower().replace('world','python')) 輸出: hello python |
split | 按某個分隔符將字串分割成序列,預設以空格符分割 |
str='1+2+3+4' print(str.split('+')) 輸出結果: ['1', '2', '3', '4'] str='HELLO WORLD' print(str.split()) 輸出結果: ['HELLO', 'WORLD'] |
strip | 去除字串兩邊的空格 |
str='HELLO WORLD' print(str.strip()) 輸出結果: HELLO WORLD |
maketrans | 建立字元對映的轉換表,接收兩個引數,第一個引數是字串,表示要轉換的字串,第二個引數也是字串表示轉換的目標(兩個引數是對映關係(一一對映),因此長度必須相同) |
intab = "el" outtab = "EL" trantab = str.maketrans(intab, outtab) str = "hello world" print (str.translate(trantab)) 輸出: hELLo worLd |
Linux公社的RSS地址 :ofollow,noindex" target="_blank">https://www.linuxidc.com/rssFeed.aspx
本文永久更新連結地址:https://www.linuxidc.com/Linux/2018-10/154608.htm