1、字符串都是不可变的
2、字符串格式化
>>>format = "Hello,%s. %s enough for ya?"
>>>values = ('world','Hot')
>>>print format % values
Hello,world.Hot enough for ya?
>>>format = "Pi with three decimal:%.3f"
>>>from math import pi
>>>print fomat % pi
Pi with three decimal:3.142
//模板字符串
>>>from string import Template
>>>s = Template('$x, glorious $x!')
>>>s.substitute(x='slurm')
"slurm, glorious slurm"
>>>s = Template("It's ${x}tastic")
>>>s.substitute(x='slurm')
"It's slurmtastic"
//简单转换
>>>'Price of eggs:$%d' % 42
'Price of eggs:$42'
>>>'Hexadecimal price of eggs:%x' % 42
'Hexadecimal price of eggs:2a'
>>>from math import pi
>>>'pi:%f...' % pi
'pi:3.141593...'
>>>'Using str:%s' % 42L
'Using str:42'
>>>'Using repr:%r' % 42L
'Using repr:42L'
//字段宽度和精度
>>>'%10f' % pi(字段宽度为10)
' 3.141593'
>>>'%10.2f' % pi(精度为2)
' 3.14'
>>>'%.2f' % pi
'3.14'
>>>'%.5s' % 'Gudio van Rossum'
'Gudio'
>>>'%.*s' % (5,'Gudio van Rossum')
'Gudio'
//符号、对齐和用0填充
>>>'%010.2f' % pi
'0000003.14'
>>>'%-10.2f' % pi #左对齐
'3.14 '
#空白“”意味着在整数前添加空格
>>>print('% 5d' % 10)+'\n'+('% 5d' % -10)
10
-10
#加号(+)添加正负号
>>>print('%+5d'% 10) +'\n'+ ('%+5d' % -10)
+10
-10
3、字符串方法
#find(在一个较长的字符串重查找子串,返回子串所在位置的最左端索引)
>>>title = "Monty Python's Flying Circus"
>>>title.find('Monty')
0
>>>title.find('Python')
6
>>>title.find('add')
-1
#带有可选的起始点和结束点参数
>>>subject = '$$$ Get rich now!!! $$$'
>>>subject.find('$$$')
0
>>>subject.find('$$$',1)
20
>>>subject.find('$$$',3,20)
-1
#join(连接序列中的元素)
>>>seq = ['1','2','3','4','5'] #不能连接数字列表
>>>sep = '+'
>>>sep.join(seq)
'1+2+3+4+5'
#lower(返回字符串的小写字母版)
>>>'Hello,World!'.lower()
'hello,world!'
#title(将所有单词的首字母大写,而其他字母小写)
#replace(返回某字符串的所有匹配项均被替换之后得到的字符串)
>>>'This is a test'.replace('is','eez')
'Theez eez a test'
#split(将字符串分割成序列)
>>>'1+2+3+4+5'.split('+')
['1','2','3','4','5']
#strip(除去两侧的空格字符串)
>>>' internal whitespace is kept '.strip()
'internal whitespace is kept'
#也可以指定需要去除的字符
>>>'***SPAM*for*everyone!!***'.strip('*!')
'SPAM*for*everyone'
#translate(替换字符串中的某些部分,与replace的是只处理单个字符)
>>>from string import maketrans
>>>table = maketrans('cs','kz')
>>>'this is an incredible test'.translate(table)
'thiz iz an inkredible tezt'
#translate第二个参数是可选的,该参数指定需要删除的字符
>>>'this is an incredible test'.translate(table,' ')
'thizizaninkredibletezt'