Format String Syntax
格式化字符串包含用花括号 {}
括起来的“可替代字段”。 花括号中不包含的所有内容均视为文字文本,该文本保持原样输出。 如果需要在文字文本中包含花括号字符,可以通过使用 {{
和 }}
来转义。
可替代字段的语法如下:
replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
field_name ::= arg_name ("." attribute_name | "[" element_index "]")*
arg_name ::= [identifier | digit+]
attribute_name ::= identifier
element_index ::= digit+ | index_string
index_string ::= <any source character except "]"> +
conversion ::= "r" | "s" | "a"
format_spec ::= <described in the next section>
format_spec ::= [[fill]align][sign][#][0][width][grouping_option][.precision][type]
fill ::= <any character>
align ::= "<" | ">" | "=" | "^"
sign ::= "+" | "-" | " "
width ::= digit+
grouping_option ::= "_" | ","
precision ::= digit+
type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
在大多数情况下,语法类似于旧的 %
格式,只是添加了 {}
,使用 :
而不是 %
。 例如,可以将 '%03.2f'
转换为 '{:03.2f}'
。
>>> print('{:o}'.format(20))
24
>>> print('{0:o}'.format(20))
24
>>> print('%o' % 20)
24
通过位置访问参数:
>>> '{0}, {1}, {2}'.format('a', 'b', 'c')
'a, b, c'
>>> '{}, {}, {}'.format('a', 'b', 'c')
'a, b, c'
>>> '{2}, {1}, {0}'.format('a', 'b', 'c')
'c, b, a'
>>> '{2}, {1}, {0}'.format(*'abc')
'c, b, a'
>>> '{0}{1}{0}'.format('abra', 'cad')
'abracadabra'
>>>
通过名字访问参数:
>>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
'Coordinates: 37.24N, -115.81W'
>>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
>>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
'Coordinates: 37.24N, -115.81W'
访问参数的属性
>>> c = 3-5j
>>> ('The complex number {0} is formed from the real part {0.real} '
'and the imaginary part {0.imag}.').format(c)
'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.'
>>> class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def __str__(self):
return 'Point({self.x}, {self.y})'.format(self=self)
>>> str(Point(4,2))
'Point(4, 2)'
关键字参数
# print() 函数有可选的变元 end 和 sep,分别指定在参数末尾打印什么,以及在参数之间打印什么来隔开它们。
# 这两个字符串出现在独立的两行中,因为 print() 函数自动在传入的字符串末尾添加了换行符
print("Hello")
print("World")
# 可以设置 end 关键字参数,指定在末尾打印什么
print("Hello", end=' ')
print("World")
# 如果向 print() 传入多个字符串值,该函数就会自动用一个空格分隔他们
print('cats', 'dogs', 'mice')
# 可以设置 sep 关键字参数,替换掉默认的字符分隔符
print('cats', 'dogs', 'mice', sep=',')
Hello
World
Hello World
cats dogs mice
cats,dogs,mice