使用字符串
- 字符串支持序列的所有操作费变,除分片賦值
- 字符串都是不可變的
格式化字符串
>>> format = "Hello, %s. %s enough for ya"
>>> values = ('world', 'hot')
>>> print format % values #Hello, world. Hot enough for ya
模板字符串
>>> from string import Template
>>> s = Template('$x, glorious $x')
>>> s.substitute(x = 'slurm') #'slurm, glorious slurm'
注:如果替換的字段是單詞的一部分亚兄,那么參數(shù)名就必須要括起來
>>> s = Template("It's ${x}tatic)
字符串格式化
- %字符:標(biāo)記轉(zhuǎn)換說明符的開始
- 轉(zhuǎn)換標(biāo)志(可選):-表示左對(duì)齊,+表示在轉(zhuǎn)換值之前要加上正負(fù)號(hào)伊诵;" "(空白字符),表示證書之前保留格式,0表示轉(zhuǎn)換值若位數(shù)不夠則用0填充
- 最小字段寬度(可選):轉(zhuǎn)換后的字符串至少應(yīng)該具有該值指定的寬度逸寓,如果是*,則寬度會(huì)從值元組中讀出轉(zhuǎn)換類型
>>> from math import pi
>>> '%10f' % pi #字段寬為10
>>> '%10.2f' % pi #字段寬10覆山,精度為2
>>> '%.2f' % pi #精度寬度為2
>>> '%.5s' % 'Guido van Rossum' #保留字符串5位
>>> '%.*s' % (5, 'Guido van Rossum') #元組中讀出參數(shù)
>>> '%010.2f' % pi #字段寬度為10竹伸,不足位數(shù)用0填補(bǔ)
>>> '%-10.2f' % pi #字段寬度為10,精度為2簇宽,左對(duì)齊
>>> '% 5d' % -10 #字段寬度為5佩伤,前面的空格用于放置-號(hào)
>>> '%+5d' % -10 #字段的寬度為5聊倔,符號(hào)位為-
字符串方法
>>> import string
>>> string.digits #0-9數(shù)字字符串
>>> string.letters #所有字母的字符串
>>> string.lowercase #所有小寫字母的字符串
>>> string.uppercase #所有大寫字母的字符串
>>> string.printable #所有可以打印的字符的字符串
>>> string.punctuation #所有標(biāo)點(diǎn)符號(hào)的字符串
find函數(shù)
>>> 'hello world, this is a new start'.find('hello') #在字符串中找到hello的位置
>>> title = "Monty Python's Flying Cricus"
>>> title.find('python') #在字符串中找到python的位置
>>> title.find('Python', 1) #在字符串中指定查找的起始位置
>>> title.find('Python', 1, 16) #在字符串中指定查找的范圍1-16
join函數(shù)
>>> seq = ['1','2','3','4']
>>> condition = '+'
>>> condition.join(seq) #用+連接字符串列表
>>> dirs = ['','usrs','bin','env']
>>> '/'.join(dirs) #用/連接地址字符串
lower函數(shù)
>>> str = 'HELLO WORLD'
>>> str.lower() #返回字符串的小寫
replace函數(shù)
>>> "it's a new test".replace('new', 'old') #將字符串中與new匹配的字符串替換為old
split函數(shù)
>>> seq = 'abcdef'
>>> seq.split() #將字符串以+為條件分割為一個(gè)列表
strip函數(shù)
>>> ' hello world '.strip() #將字符串兩側(cè)的空格刪除
>>> '#!#!get a high #! score#!#!'.strip('#!') #將字符串兩側(cè)的#!刪除
translate函數(shù)
>>> from string import maketrans
>>> table = maketrans('cs', 'kz') #創(chuàng)建轉(zhuǎn)換表
>>> 'this is side'.translate(table) #轉(zhuǎn)換
注:與replace相比生巡,translate函數(shù)只處理單個(gè)字符
capwords函數(shù)
>>> print(string.capwords("hello world", " ").replace(" ", "-")) #將字符串每個(gè)單詞首字母大寫并以-分割