Python笔记-文本字符串格式化

来源:互联网 发布:ubuntu论坛 编辑:程序博客网 时间:2024/04/29 19:46

文本字符串格式化

Python 有两种格式化字符串的方式,旧式和新式。

1、使用%的旧式格式化

>>> '%s' % 42'42'>>> '%d' % 42'42'>>> '%f' % 7.03'7.030000'>>> '%e' % 7.03'7.030000e+00'>>> '%d%%' % 100'100%'>>> actor = 'Richard Gere'>>> "My wife's favorite actor is %s" % actor"My wife's favorite actor is Richard Gere">>> cat = 'Chester'>>> weight = 28>>> "Our cat %s weighs %s pounds" % (cat, weight)'Our cat Chester weighs 28 pounds'

字符串中出现 % 的次数需要与 % 之后所提供的数据项个数相同。

如果只需插入一个数据,例如前面的 actor, 直接将需要插入的数据置于% 后即可。

如果需要插入多个数据,则需要将它们封装进一个元组,例如上例中的 (cat, weight)。

>>> n = 42>>> f = 7.03>>> s = 'string cheese'#设定最小域宽为10个字符,最大字符宽度为4,右对齐>>> '%10.4d %10.4f %10.4s' % (n, f, s)'      0042       7.0300       stri'

2、使用{}和format的新式格式化

>>> n = 42>>> f = 7.03>>> s = 'string cheese'>>> '{} {} {}'.format(f, n, s)'7.03 42 string cheese'>>> '{2} {0} {1}'.format(f, s, n)'42 7.03 string cheese'>>> '{n} {f} {s}'.format(n=42, f=7.03, s='string cheese')'42 7.03 string cheese'

旧式格式化允许在 % 后指定参数格式,但在新式格式化里,将这些格式标识符放在 : 后

>>> n = 42>>> f = 7.03>>> s = 'string cheese'>>> '{0:d} {1:f} {2:s}'.format(n, f, s)'42 7.030000 string cheese'>>> '{n:d} {f:f} {s:s}'.format(n=42, f=7.03, s='string cheese')'42 7.030000 string cheese'#最小域宽设为10。   <:右对齐    >:左对齐    ^:居中>>> '{0:>10d} {1:>10f} {2:>10s}'.format(n, f, s)' 42 7.030000 string cheese'

3、对于浮点数而言精度仍然代表着小数点后的数字个数, 对于字符串而言精度则代表着最大字符个数,但在新式格式化中你无法对整数设定精度:

>>> '{0:>10.4d} {1:>10.4f} {2:10.4s}'.format(n, f, s)Traceback (most recent call last):File "<stdin>", line 1, in <module>ValueError: Precision not allowed in integer format specifier>>> '{0:>10d} {1:>10.4f} {2:>10.4s}'.format(n, f, s)' 42 7.0300 stri'
0 0
原创粉丝点击