python中的字符串格式化

时间:2023-03-09 08:41:36
python中的字符串格式化

Python中常见的字符串格式化方式包括两种:字符串插入(str%),format函数(str.format())

1、字符串插入

字符串插入是设置字符串格式的简单方法,与C语言、Fortran语言差别不大。示例如下:

>>> a, b, c = 'cat', 6, 3.14
>>> s = 'There\'s %d %ss older than %.2f years.' % (b, a, c)
>>> s
"There's 6 cats older than 3.14 years."

一些转换说明符见下表:

d 整数
o 八进制数
x 小写十六进制数
X 大写十六进制数
e 小写科学记数浮点数
E 大写科学计数浮点数
f 浮点数
s 字符串
% %字符

2、format函数

字符串函数format()是灵活构造字符串的方法。

  • 命名替换
>>> s = 'My {pet} has {prob}.'.format(pet = 'dog', prob = 'fleas')
>>> s
'My dog has fleas.'
  • 位置替换
>>> s = 'My {0} has {1}.'.format('dog', 'fleas')
>>> s
'My dog has fleas'

一些灵活的用法:

#使用转换说明符
>>> print('1/81 = {x:.3f}'.format(x = 1/81))
1/81 = 0.012
#可以通过变量设定格式参数,字符串插入无法做到这点
>>> print('1/81 = {x:.{d}f}'.format(x = 1/81, d = 5))
1/81 = 0.01235
#x!r,x!s的意思分别指:repr(x),str(x)
>>> '({0!r}, {0!s})'.format('test')
"('test', test)"
#特别的,千位金额输出数字,遇到才知道有这种用法
>>> '{:,}'.format(987654)
'987,654'

总结

对于创建格式简单的字符串,字符串插入方式足够直观、简便;format函数可更灵活、强大地构造字符串,适合庞大、复杂的工作,如创建网页等。