《python基础教程》读书笔记第三章-字符串的使用

 

所有的标准序列操作对字符串都适用:索引,分片,乘法,判断成员资格,求长度,最小值和最大值。


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.打印购物小票程序

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)

运行结果:

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等方法,参见书本附录。

>>> '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方法

本章小结:主要是字符串格式化和字符串方法

你可能感兴趣的:(《python基础教程》读书笔记第三章-字符串的使用)