使用str.format()
或者str%()
来实现格式化字符串。
- 一般用法
>>> name_v = '小黑'
>>> title_v = '笨蛋'
>>> string1 = '{name}是最大的{title}'.format(name=name_v, title=title_v)
>>> string2 = '%s是最大的%s'%(name_v, title_v)
>>> print(string1)
小黑是最大的笨蛋
>>> print(string2)
小黑是最大的笨蛋
注意:如果格式化的字符串中本身有{
或}
,需要变成{{
或}}
>>> string = '{{}}被用来表示一个{}'.format('参数')
>>> print(string)
{}被用来表示一个参数
建议 :在字符串本身包含较多 { 或 } 时可以使用str%()
格式
- 格式化
# 冒号(:)右边的内容表示显示格式
# >表示右对齐
# 0表示填充符号
# 3表示最小输出宽度为3位
>>> '{:>03}'.format(5)
'005'
# <表示右对齐
>>> '{:<03}'.format(5)
'500'
# 默认空格填充
>>> '{:<3}'.format(5)
'5 '
# 保留两位有效数字(只用于浮点数)
>>> '{:.2}'.format(554.45488)
'5.5e+02'
# 保留两位小数
>>> '{:.2f}'.format(554.45488)
'554.45'
# 科学计数法保留两位小数
>>> '{:.2e}'.format(554.45488)
'5.54e+02'
部分文档
format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type]
fill ::= <any character>
align ::= "<" | ">" | "=" | "^"
sign ::= "+" | "-" | " "
width ::= integer
precision ::= integer
type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
#一些例子
# 对齐和填充(指定宽度对齐才能生效)
>>> '{:<30}'.format('left aligned')
'left aligned '
>>> '{:>30}'.format('right aligned')
' right aligned'
>>> '{:^30}'.format('centered')
' centered '
>>> '{:*^30}'.format('centered') # use '*' as a fill char
'***********centered***********'
# 数值前的正负号显示方式
>>> '{:+f}; {:+f}'.format(3.14, -3.14) # show it always
'+3.140000; -3.140000'
>>> '{: f}; {: f}'.format(3.14, -3.14) # show a space for positive numbers
' 3.140000; -3.140000'
>>> '{:-f}; {:-f}'.format(3.14, -3.14) # show only the minus -- same as '{:f}; {:f}'
'3.140000; -3.140000'
# 使用不同进制显示并控制进制前缀的输出
>>> # format also supports binary numbers
>>> "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42)
'int: 42; hex: 2a; oct: 52; bin: 101010'
>>> # with 0x, 0o, or 0b as prefix:
>>> "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42)
'int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010'
# 逗号分割大整数
>>> '{:,}'.format(1234567890)
'1,234,567,890'
# 百分数形式输出
>>> points = 19.5
>>> total = 22
>>> 'Correct answers: {:.2%}'.format(points/total)
'Correct answers: 88.64%'
完整文档请在python命令行中执行如下命令查看 ( FORMATTING两边的分号是必要的 )
help('FORMATTING')