1.字符串格式化操作符(%)格式化字符串
format = 'hello %s.greeting %s.'#%s表示值会被格式化为字符串 values = ('world','you')#可以是元组也可以是字典 print(format % values)
2.格式化实数(浮点数)
from math import pi format = 'Pi with three decimals: %.3f'#精确小数点后三位 print(format % pi)
3.关于format的用法:
foo = '{0} love {1},it\'s {2}'.format('I','you','python') print(foo) #'{a} love {b},it\'s {c}'.format('I','you','python')这个是错误的代码,注意区别 foo = '{0} love {b},it\'s {c}'.format('I',b = 'you',c = 'python')#注意{0} print(foo)
4.substitute(模版字符串)
from string import Template s = Template('$x,glorious $x!') print(s.substitute(x = 'slurm'))
替换字段是单词的一部分
from string import Template s = Template('It\'s ${x}tastic!') print(s.substitute(x = 'slurm'))
插入美元符号$$
from string import Template s = Template('Make $$ selling $x!') print(s.substitute(x = 'slurm'))
还可以使用字典
from string import Template s = Template('A $thing must never $action,') d = {} d['thing'] = 'gentleman' d['action'] = 'show his socks' print(s.substitute(d))
SB的全称是smart boy