字符串格式化输出

模板字符串(简化格式设置),python自带的简单字符串格式化输出方式:

>>> from string import Template
>>> tmpl = Template("Hello, $who! $what enough for you?")
>>> tmpl.substitute(who='Mars', what='Dusty')
'Hello, Mars! Dusty enough for you?'
>>> tmpl = Template("Hi $name, welcome to $city!")
>>> data = {
... 'name':'Jack',
... 'city':'Beijing'
... }
>>> tmpl.substitute(**data)
'Hi Jack, welcome to Beijing!'

format设置字符串格式:

  千位分隔符:可使用逗号来添加千位分隔符。若同时指定其他格式设置元素时,逗号应放在宽度和表示精度的句点之间。

>>> '{:,}'.format(10 ** 50)
'100,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000'
>>> '{:40,.2f}'.format(10 ** 20)
'          100,000,000,000,000,000,000.00'

  符号、填充:可使用填充字符来填充对齐说明符,这样将使用指定的字符而不是默认的空格来填充。

>>> '{:$^10}'.format('Hello')
'$$Hello$$$'
>>> '{:$>10}'.format('Hello')
'$$$$$Hello'
>>> '{:$<10}'.format('Hello')
'Hello$$$$$'

  更具体的说明符=,它指定将填充字符放在符号和数字之间。

>>> from math import pi
>>> '{:10.2f}'.format(-pi)
'     -3.14'
>>> '{:=10.2f}'.format(-pi)
'-     3.14'
>>> '{:$=10.2f}'.format(-pi)
'-$$$$$3.14'

  要给数加上符号,可使用说明符+(将其放在对齐说明符后面)。

>>> '{}'.format(3.3)
'3.3'
>>> '{}'.format(+3.3)
'3.3'
>>> '{:+}'.format(3.3)
'+3.3'
>>> '{:>+10}'.format(3.3)
'      +3.3'

  #号选项,可将其放在符号说明符和宽度之间。它将触发另一种转换方式,转换细节随类型而异。

  例如,对于二进制、八进制、十六进制转换,将加上一个前缀。对于十进制,它要求必须包含小数点(对于类型g,它保留小数点后面的零)。

>>> '{:#10b}'.format(42)
'  0b101010'
>>> '{:+#10b}'.format(42)
' +0b101010'
>>> '{:b}'.format(42)
'101010'
>>> '{:#b}'.format(42)
'0b101010'
>>> '{:#10b}'.format(42)
'  0b101010'
>>> '{:+#10b}'.format(42)
' +0b101010'
>>> '{:g}'.format(42)
'42'
>>> '{:#g}'.format(42)
'42.0000'

  在python 3.6中,如果变量和替换字段同名,还可以使用一种简写,可使用f字符串,即在字符串前面加上f。

>>> from math import e
>>> "Euler's constant is roughly {e}.".format(e=e)
"Euler's constant is roughly 2.718281828459045."
>>> f"Euler's constant is roughly {e}."
"Euler's constant is roughly 2.718281828459045."
>>> name = 'name'
>>> f'This is an English word : {name}'
This is an English word : name

 

posted @ 2018-09-01 20:59  从python开始  阅读(568)  评论(0)    收藏  举报