1 s='http://www.baidu.com'
2 s[-3:]='aaa'
3 print(s)
输出结果:
1 s[-3:]='aaa'
2 TypeError: 'str' object does not support item assignment
可以看出抛出的错误信息,字符串不允许标记内部项。
但我们可以在字符串中用一个百分比符号%s标记出一个占位符,它表示我们将要在该位置插入转换值的位置。s将会被格式化为字符串,如果被转换的对象不是字符串,则会将其转换为字符串。
除了用%s插入转换值外,还可以使用substitute模板方法,用传递进来的关键字参数替换字符串中的关键字。
1 from string import Template
2 s=Template('$x,glorious $b')
3 s=s.substitute(x='slurm',b='haha')
4 print(s)
输出结果:
我们看到$s位置被替换为slurm,$b位置被替换为haha
如果被替换的位置是单词的一部分,可以将其用{}括起来
1 from string import Template
2 s=Template('${x}glorious $b')
3 s=s.substitute(x='slurm',b='haha')
4 print
输出结果:
使用字典变量提供值得/名称对替换
1 from string import Template
2 s=Template('$name come from $county ')
3 d={}
4 d['name']='zhangsan'5 d['county']='china'6 s=s.substitute(d)
7 print(s)
输出结果:
1 s='%s come from %s'%('zhangsan','china')
2 print(s)
输出结果:
1 zhangsan come from china
字符串与utf8互转
1 s='你好'
2 print(s.encode('utf8'))
3 a=s.encode('utf8')
4 print(a.decode('utf8'))
输出结果:
1 b'\xe4\xbd\xa0\xe5\xa5\xbd'
2 你好
宽度是指转换后的值所保留的最小字符个数,精度则是结果中应该包含的小数位数
例如 输出宽度为10的pi的值
1 from math import pi
2 p='%10f'%pi
3 for k, i in enumerate(p) : #使用enumerate函数打印序列
4 print('序列%s'%k,i)
打印精度为2的pi的值
1 from math import pi
2 p='%.2f'%pi
3 print(p)
输出结果:
打印宽度为10,精度为2的pi的值
1 from math import pi
2 p='%10.2f'%pi
3 for k,i in enumerate(p):
4 print('序列%s 打印值%s'%(k,i))
打印结果:
1 序列0 打印值
2 序列1 打印值
3 序列2 打印值
4 序列3 打印值
5 序列4 打印值
6 序列5 打印值
7 序列6 打印值3
8 序列7 打印值.
9 序列8 打印值1
10 序列9 打印值4
我们看到,当整数部分没有值时,将以空' ' 代替。
1 print('%+5d'%10)
2 print('%+5d'%-10)
输出:
1 +10
2 -10
使用字符串格式化,使我们的代码看着更简洁
1 width=input('>>输入宽度:')
2 price_with=10
3 item_width=int(width)-price_with
4 header_format='%-*s%*s'
5 format='%-*s%*.2f'
6 print('='*int(width))
7 print(header_format%(item_width,'item',price_with,'price'))
8 print('_'*int(width))
9 print(format%(item_width,'apple',price_with,0.4))
10 print(format%(item_width,'Pears',price_with,0.5))
输出结果:
>>输入宽度:30
==============================
item price
______________________________
apple 0.40
Pears 0.50