Python 中的字符串格式化

String Formatting in Python

Posted by J Leaves on March 13, 2020

本文介绍 Python 中的字符串格式化的参数语法,以及字符串格式化的两种写法。

基础:格式规格 Format Spec

见博文格式规格 Format Spec

方法一:使用 % 格式化(类似C)

用 % 来格式化,在很多语言中都被使用。(由 IEEE Standard 规定)

1
"FIRST:%s, SECOND:%d, THIRD:%.2f, FOURTH:%5.2f" % (1.3456, 2.6735, 3.1904, 4.0927)
1
'FIRST:1.3456, SECOND:2, THIRD:3.19, FOURTH: 4.09'

Python 式的格式化语法 Pythonic Format String Syntax

Python 中,还有另一种特有的字符串格式化的方法。

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。

方法二:使用 str.format() 格式化

以下为使用 str.format() 来格式化的例子:

1
'{}, {}, {}'.format('a', 'b', 'c')
1
'a, b, c'

使用 field_name

1
'{0}, {2}, {1}'.format('a', 'b', 'c')
1
'a, c, b'
1
'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
1
'Coordinates: 37.24N, -115.81W'

使用 format_spec

1
'{:.5} and {:.4}'.format('beautiful', 'fantastic')
1
'beaut and fant'
1
'{1:.4} and {0:.5}'.format('beautiful', 'fantastic')
1
'fant and beaut'

使用 conversion

1
'{1!s} and {0}'.format(1, '繁星')
1
'繁星 and 1'
1
'{1!r} and {0}'.format(1, '繁星')
1
"'繁星' and 1"
1
'{1!a} and {0}'.format(1, '繁星')
1
"'\\u7e41\\u661f' and 1"

str.format(<string>, <format_spec>)<string>.format(<format_spec>) 使用相同的一套参数。

1
str.format("FIRST:{:f}, SECOND:{:.0f}, THIRD:{:.2f}, FOURTH:{:5.2f}", 1.3456, 2.6735, 3.1904, 4.0927)
1
"FIRST:{:f}, SECOND:{:.0f}, THIRD:{:.2f}, FOURTH:{:5.2f}".format(1.3456, 2.6735, 3.1904, 4.0927)
1
'FIRST:1.345600, SECOND:3, THIRD:3.19, FOURTH: 4.09'