Python字符串的格式化方法

Python字符串格式化有多种方法。

完全手工构造

配合使用切片,连接,以及一些str的方法,完全手工的方式构造字符串。
常用的字符串排版方法:

  • str.rjust(width[, fillchar]) 返回用空格或指定字符右对齐str到指定宽度的新str
  • str.ljust(width[, fillchar]) 返回用空格或指定字符左对齐str到指定宽度的新str
  • str.center(width[, fillchar]) 返回用空格或指定字符居中对齐str到指定宽度的新str
  • str.zfill(width) 返回用0填充到指定宽度的新str

通过str对象的方法

str.format()

通过使用{}指明格式化域

位置参数格式化

>>> print('We are the {} who say "{}!"'.format('knights', 'Ni'))
We are the knights who say "Ni!"

>>>
>>> print('{0} and {1}'.format('spam', 'eggs'))
spam and eggs
>>> print('{1} and {0}'.format('spam', 'eggs'))
eggs and spam

关键字参数格式化

>>> print('This {food} is {adjective}.'.format(
...       food='spam', adjective='absolutely horrible'))
This spam is absolutely horrible.

位置参数和关键字参数可以一起使用

>>> print('The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred',
                                                       other='Georg'))
The story of Bill, Manfred, and Georg.

格式指示符

在格式化域名之后使用可选的格式指示符(format specifer)可以进一步控制格式化。

格式化域中使用’!a’ (应用 ascii()), ‘!s’ (应用 str()) and ‘!r’ (应用 repr()) 可实现在格式化前应用对应的转换

>>> contents = 'eels'
>>> print('My hovercraft is full of {}.'.format(contents))
My hovercraft is full of eels.
>>> print('My hovercraft is full of {!r}.'.format(contents))
My hovercraft is full of 'eels'.

格式化域中使用:format specifer的形式控制小数长度,字符宽度。

:3f让PI四舍五入到小数点后第三位

>>> import math
>>> print('The value of PI is approximately {0:.3f}.'.format(math.pi))
The value of PI is approximately 3.142.

: 后加整数指明所格式化的域的最小字符宽。

>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
>>> for name, phone in table.items():
...     print('{0:10} ==> {1:10d}'.format(name, phone))
...
Jack       ==>       4098
Dcab       ==>       7678
Sjoerd     ==>       4127

直接读取字典

>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; '
...       'Dcab: {0[Dcab]:d}'.format(table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678

通过解包读取字典

>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678

老的字符串格式法

利用%操作符格式化

>>> import math
>>> print('The value of PI is approximately %5.3f.' % math.pi)
The value of PI is approximately 3.142.

格式化字符串字面量

python3.6引入的格式化方法-格式化字符串字面量(f-strings)。

格式化字符字面量的定义和用rR作为字符串前缀的原型字符串类似,用’f’或’F’做为前缀。在字符串中可以使用{expression}的语法引用变量。

>>> import math
>>> print(f'The value of pi is approximately {math.pi:.3f}.')
The value of pi is approximately 3.142.

expression后面可以加格式指示符实现更精细的格式控制,指示符语法类似str.format

Template类

string模块的Template类也可用于格式化。

Template中用于表示占位符的语法默认为$identifier${identifier},和str.format不一样,不过可以通过继承Template实现自己的语法。

$$表示$本身,默认情况下identifier需要时ascii中的字母,数字或下划线,可以是_和字符开头。

Template有两个主要的公有方法,:

  • substitute() 用指定的值替换模板中的占位符,如果有占位符没匹配,则抛出KeyError
  • safe_substitute() 占位符不匹配时不抛出异常的,可随意出现$符号的版本

通过调用上述两个方法实现模板字符串的格式化。

>>> from string import Template
>>> s = Template('$who likes $what'
)>>> s.substitute(who='tim', what='kung pao')
'tim likes kung pao'
>>> d = dict(who='tim')
>>> Template('Give $who $100').substitute(d)
Traceback (most recent call last):
...ValueError: Invalid placeholder in string: line 1, col 11
>>> Template('$who likes $what').substitute(d)
Traceback (most recent call last):
...KeyError: 'what'
>>> Template('$who likes $what').safe_substitute(d)
'tim likes $what'
发布了106 篇原创文章 · 获赞 15 · 访问量 15万+

猜你喜欢

转载自blog.csdn.net/skyupward/article/details/104830594