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 hor