# 《Python基础教程》第3章 字符串操作

### 基本字符串操作

``````website = 'http://python.org'
website[-3:] = 'com' //TypeError
``````

### 字符串格式化：精简版

``````>>> format = "hello, %s"
>>> values  =('world')
>>> format % values
'hello, world'

>>> format = "Pi with three decimals: %.3f"
>>>from math import pi
>>>print format % pi
Pi with three decimals: 3.142
``````

%s是期望接受字符串，%.3f期望接受小数点后有三位的浮点数。

### 字符串格式化：完整版

（1）%：转换说明符的开始
（2）转换标识（可选）: -/+/' '/0
（3）最小字段宽度
（4）(.)：后跟精度值
（5）转换类型：......

###### 简单转换

>>> 'Price of eggs: \$%d' % 42

>>> 'Price of eggs: %x' % 42

>>> from math import pi
>>> 'Pi: %f......' % pi

>>> from math import pi
>>> 'Very inexact estimate of Pi: %i' % pi

>>> 'Using str: %s' % 42L

>>> 'Using repr: %s' % repr(42L) 或 'Using repr: %r' % 42L

###### 字段宽度和精度
``````>>> '%10.2f'%pi
'      3.14' #字段宽为10，精度为2
>>> '%10f'%pi
'  3.141593' #字段宽为10
>>> '%.*s' % (5,'Gui Vanchi')
'Gui V' #使用*会从右操作数中去读取参数
``````
###### 符号、对齐和0填充
``````>>> '%010.2f'%pi
'0000003.14' #在字符宽度前加0会将结果前面的空格用0填充
>>> '%-10.2f'%pi
'3.14    ' #加-号会使结果左对齐
>>> print('% 5d' % 10) + '\n' + ('% 5d' % -10)
10
-10 # 加‘ ’可以方便同样的缩进
>>> print('%+5d' % 10) + '\n' + ('%+5d' % -10)
+10
-10 #加+可以保证结果中包含正负有同样的缩进
``````

Screen Shot 2015-01-07 at 1.58.39 PM.png

``````width = int(raw_input('Please enter with:'))
print '=' * width
print 'Item' + '% *s' % (width - len('Item'), 'Price')
print '-' * width
print 'Apples' + '% *s' % (width - len('Prices'), '0.40')
print 'Pears' + '% *s' % (width - len('Pears'), '0.50')
print 'Cantaloupes' + '% *s' % (width - len('Cantaloupes'), '1.92')
print 'Dried Apricots (16 oz. )' + '% *s' % (width - len('Dried Apricots (16 oz. )'), '8.00')
print 'Prunes (4 lbs. )' + '% *s' % (width - len('Prunes (4 lbs. )'), '12.00')
print '=' * width
``````

``````width = int(raw_input('Please enter with:'))
price_width  = 10
item_width = width - price_width
list_format = '%-*s%*.2f'
print '=' * width
print head_format % (item_width, 'Item', price_width, 'Price')
print '-' * width
print list_format % (item_width, 'Apples', price_width, 0.4)
print list_format % (item_width, 'Pears', price_width, 0.5)
print list_format % (item_width, 'Cantaloupes', price_width, 1.92)
print list_format % (item_width, 'Dried Apricots (16 oz. )', price_width, 8.00)
print list_format % (item_width, 'Prunes (4 lbs. )', price_width, 12)
print '=' * width
``````

### 字符串方法

• find()
find方法提供了在字符串中查找子字符串的功能，找到了返回子字符串左端索引，否则返回-1。还可以指定查找范围：通过指定开始索引位置和终止索引位置。

``````>>> sentence = 'Klay Thompson is as smart of a defender as it gets.'
>>> sentence.find('Thompson')
5
>>> sentence.find('Lebron')
-1
>>> sentence.find('Thompson', 8)
-1
``````
• join()

join方法是split方法的逆方法，join的列表中必须都是字符串。

``````>>> seq = [1,2,3,4,5]
>>> ','.join(seq) //TypeError

>>> seq = ['1','2','3','4', '5']
>>> ','.join(seq)
'1,2,3,4,5'

>>> dirs = '', 'usr', 'bin', 'env'
>>> '/'.join(dirs)
'/usr/bin/env'

>>> print 'C:'  + '\\'.join(dirs)
C:\usr\bin\env
``````
• lower()

``````>>> 'The defensive philosophies of Klay Thompson'.lower()
'the defensive philosophies of klay thompson'
``````
• replace()

``````>>> 'This is an egg'.replace('is', 'ezz')
'Thezz ezz an egg' #替换所有匹配项
``````
• split()

``````>>> '1,2,3,4,5'.split(',')
['1', '2', '3', '4', '5']

>>> '/usr/bin/env'.split('/')
['', 'usr', 'bin', 'env']

>>> 'Using the default'.split()
['Using', 'the', 'default']
``````
• strip()

``````>>> ' Thompson read it easily. '.strip()
``````
• translate()

``````>>> from string import maketrans
>>> table = maketrans('cs', 'kz')
>>> 'This is an incredible test'.translate(table)
'Thiz iz an inkredible tezt'
>>> 'This is an incredible test'.translate(table,' ')
'Thizizaninkredibletezt'
``````

maketrans指定了要替换的字符匹配关系，将得到的table作为参数传递给translate就可以进行“多”字符的替换了。其中第二个参数可以指定要删除的字符串。