?
所有的標(biāo)準(zhǔn)序列操作對(duì)字符串都適用:索引灾锯,分片葬凳,乘法绰垂,判斷成員資格,求長(zhǎng)度火焰,最小值和最大值劲装。
1.字符串直接賦值
>>> website = 'http://www.baidu.com'
>>> website[-3:]
'com'
2.字符串格式化
>>> format = 'hello,%s.%s enough for ya?'
>>> values = ('world','hot')
>>> print(format % values)
hello,world.hot enough for ya?
>>> 'price of book of pythen $%d' %67
'price of book of pythen $67'
>>> 'price of book of pythen in 0x format $%x' %67
'price of book of pythen in 0x format $43'
>>> 'price of book of pythen in 0o format $%o' %67
'price of book of pythen in 0o format $103'
eg.打印購(gòu)物小票程序
w = int(input('please input width:'))
price_w = 10
item_w = w - price_w
header_format = '%-*s%*s'
format? ? ? ? = '%-*s%*.2f'
print('='*w)
print( header_format%(item_w,'Item',price_w,'price'))
print('-'*w)
print(format % (item_w,'Apple',price_w,0.4))
print(format % (item_w,'Pears',price_w,0.5))
print(format % (item_w,'Cantaloupes',price_w,2.98))
print(format % (item_w,'Dried Apricots(16 oz)',price_w,16))
print(format % (item_w,'Prunes(4 1bs)',price_w,17.4))
print(format % (item_w,'Total Sum',price_w,17.4+16+2.98+0.5+0.4))
print('='*w)
運(yùn)行結(jié)果:
please input width:40
========================================
Item? ? ? ? ? ? ? ? ? ? ? ? ? ? ? price
----------------------------------------
Apple? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 0.40
Pears? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 0.50
Cantaloupes? ? ? ? ? ? ? ? ? ? ? ? 2.98
Dried Apricots(16 oz)? ? ? ? ? ? ? 16.00
Prunes(4 1bs)? ? ? ? ? ? ? ? ? ? ? 17.40
Total Sum? ? ? ? ? ? ? ? ? ? ? ? ? 37.28
========================================
3.字符串的方法
find方法
>>> s = "i have 10 $ in my pocket"
>>> s
'i have 10 $ in my pocket'
>>> s.find('poc')
18
>>> s.find('tes')
-1
>>> subject = '$$$ get rich now !!!$$$'
>>> subject.find('$$$')
0
>>> subject.find('$$$',1)
20
>>> subject.find('$$$',1,20)
-1
join方法
>>> dirs = ['','usr','bin','env']
>>> '/'.join(dirs)
'/usr/bin/env'
lower方法
>>> dir = '/USR/LOCAL/BIN'
>>> dir.lower()
'/usr/local/bin'
另外還有islower capitalize swapcase istitle upper isupper等方法,參見(jiàn)書(shū)本附錄昌简。
>>> 'i want to study python'.title()
'I Want To Study Python'
>>> 'i want to study python'.upper()
'I WANT TO STUDY PYTHON'
replace方法
>>> 'this is a test to study replace method'.replace('a','f')
'this is f test to study replfce method'
split方法
>>> '/usr/bin/env'.split('/')
['', 'usr', 'bin', 'env']
strip方法
>>> '? ? this is a test to study strip method? ? '.strip()
'this is a test to study strip method
>>> '*******spam*for*everyone!!!!!*****'.strip('!*')
'spam*for*everyone'
translate方法
本章小結(jié):主要是字符串格式化和字符串方法