python 字符串的格式化
2018-10-17 本文已影响0人
tafanfly
- 使用
%s
作为占用符
>>> 'Hello, %s' % 'World'
'Hello, World'
当然还有其他的占用符可以使用, 比如%d
(十进制整数), %f
(浮点数)等
>>> 'I am %d years old' % 20
'I am 20 years old'
>>> 'I am %d year old' % '20'
Traceback (most recent call last):
File "<input>", line 1, in <module>
'I am %d year old' % '20'
TypeError: %d format: a number is required, not str
>>> 'Pi is %f' % 3.1415
'Pi is 3.141500'
>>> 'Pi is %.3f' % 3.1415
'Pi is 3.142'
- 使用
{}
作为占用符
>>> 'Hello, {}'.format('World')
'Hello, World'
>>> 'I {} {} years old'.format('am', 20)
'I am 20 years old'
>>> 'I {} {} years old'.format('am', '20')
'I am 20 years old'
>>> 'I {am} {age} years old'.format(am='am', age=20)
'I am 20 years old'
- 字典格式
>>> 'I am %(age)s' % {'age': 20}
'I am 20'