一、%
在%左边指定一个字符串(格式字符串),并在右边指定要设置其格式的值。
>>> format = "Hello, %s. %s enough for ya?"
>>> values = ('world', 'Hot')
>>> format % values
'Hello, world. Hot enough for ya?'
二、模板字符串
>>> from string import Template
>>> tmpl = Template("Hello, $who! $what enough for ya?")
>>> tmpl.substitute(who="Mars", what="Dusty")
'Hello, Mars! Dusty enough for ya?'
三、每个替换字段都用花括号括起
1、替换字段没有名称或将索引用作名称
>>> "{}, {} and {}".format("first", "second", "third")
'first, second and third'
2、索引、无需按顺序排列
>>> "{0}, {1} and {2}".format("first", "second", "third")
'first, second and third'
>>> "{3} {0} {2} {1} {3} {0}".format("be", "not", "or", "to")
'to be or not to be'
3、有命名字段
>>> from math import pi
>>> "{name} is approximately {value:.2f}.".format(value=pi, name="π")
'π is approximately 3.14.'
在Python 3.6中,如果变量与替换字段同名,还可使用一种简写。在这种情况下,可使用f字符串——在字符串前面加上f
>>> from math import e
>>> f"Euler's constant is roughly {e}."
"Euler's constant is roughly 2.718281828459045."
等价于
>>> "Euler's constant is roughly {e}.".format(e=e)
"Euler's constant is roughly 2.718281828459045."
-----------------------
以上种种让我想起了Linux的shell,看来Python可能还真是个能用来写脚本的货。