Python格式化字符串format

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

0. 测试环境

Python 3.6.9

1. 引言

Python中格式化字符串的方式有,一种是用%操作符来进行字符串格式化,一种是使用str.format()来进行字符串格式化,本文主要介绍str.format()方式,这种方式更主流,也是官方推荐的方式,%的方式后面会逐渐淘汰。

2. 格式化字符串

2.1 基本语法

格式化字符串包含用大括号{}括起来的“替换字段”,。大括号中不包含的内容被视为正常文本,会原样输出。注意:如果要在文本中输出大括号,需要使用来转义,不是使用场景的转义字符\。示例如下:

1
2
3
4
>>> 'This is a format {}.'.format('test')
'This is a format test.'
>>> 'This is {{}} test.'.format()
'This is {} test.'

下面是“替换字段”的语法,后面的示例中会具体讲到:

1
2
3
4
5
6
7
8
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>

2.2 位置参数标识符

格式化字符串中,默认情况下{}中可以不加位置标识符,即'{} {}'.format(a, b)'{0} {1}'.format(a, b)是等价的,但如果位置标识符在字符串中不是按参数顺序出现的,则需要显示的指明位置标识符。示例代码如下:

1
2
3
4
5
6
7
8
>>> '{0} {1}'.format('one', 'two')
'one two'
>>> '{} {}'.format('one', 'two')
'one two'
>>> '{1} {0}'.format('one', 'two')
'two one'
>>> '{0} {1} {0}'.format('one', 'two')
'one two one'

2.3 设置参数

格式化字符串中可以使用变量、字典、列表索引、类的属性等来设置参数。示例代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
print('Name: {name}, URL: {url}'.format(name='Tyan', url='http://noahsnail.com'))

name = 'Tyan'
url = 'http://noahsnail.com'
print('Name: {}, URL: {}'.format(name, url))

site = {'name' : 'Tyan', 'url' : 'http://noahsnail.com'}
print('Name: {site[name]}, URL: {site[url]}'.format(site=site))
print('Name: {name}, URL: {url}'.format(**site))

site = ['Tyan', 'http://noahsnail.com']
print('Name: {0[0]}, URL: {0[1]}'.format(site))

class Test(object):
def __init__(self):
self.name = 'Tyan'
self.url = 'http://noahsnail.com'

print('Name: {0.name}, URL: {0.url}'.format(Test()))

site = {'name' : 'Tyan', 'url' : 'http://noahsnail.com'}
print('Name: {name}, URL: {url}'.format(**site))

# Output
Name: Tyan, URL: http://noahsnail.com
Name: Tyan, URL: http://noahsnail.com
Name: Tyan, URL: http://noahsnail.com
Name: Tyan, URL: http://noahsnail.com
Name: Tyan, URL: http://noahsnail.com
Name: Tyan, URL: http://noahsnail.com
Name: Tyan, URL: http://noahsnail.com

2.3 转换标志(conversion)

转换标志以!开始,主要有三种!s!r!a,分别会调用参数对象的__str____repr____ascii__方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Test(object):

def __str__(self):
return 'Test str function.'


def __repr__(self):
return 'Test repr function.'


def __ascii__(self):
return 'Test ascii function.'


print('str: {t!s}, repr: {t!r}, ascii: {t!a}'.format(t=Test()))

# Ouput
str: Test str function., repr: Test repr function., ascii: Test repr function.

2.4 格式化说明(format_spec)

格式化说明包含了值表示的说明,包括字段宽度、对其方式、填充、小数准确率等,其以:开头。标准格式化说明符的一般形式为:

1
2
3
4
5
6
7
8
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" | "%"
  • <表示输出结果左对齐,>是右对齐,^是居中对其,=表示填充值在符号之后数字之前,例如+00001234
  • +表示正负数字都要带符号,-表示只有负数需要带负号, 表示正数前面带空格,负数前面带负号。
  • 数字表示。b表示二进制格式,c表示将整数转换为字符,d表示十进制整数,o表示八进制格式,x,X表示十六进制格式,x大于9的字母为小写,X大于9的字母为大写。默认为d
  • 其它说明符的具体解释可参考文档[1]。

示例及结果如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
print('{:<8}'.format('1234'))
print('{:>8}'.format('1234'))
print('{:^8}'.format('1234'))

print('{:*>8}'.format('1234'))
print('{:*<8}'.format('1234'))
print('{:*^8}'.format('1234'))

print('{:+f}; {:+f}'.format(3.14, -3.14))
print('{: f}; {: f}'.format(3.14, -3.14))
print('{:-f}; {:-f}'.format(3.14, -3.14))

print('int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}'.format(100))
print('int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}'.format(100))

print('{:,}'.format(100000000))

print('{:.2e}'.format(100000000))

print('percentage: {:.2%}'.format(1 / 3))


import datetime
print('{:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now()))


# Output
1234
1234
1234
****1234
1234****
**1234**
+3.140000; -3.140000
3.140000; -3.140000
3.140000; -3.140000
int: 100; hex: 64; oct: 144; bin: 1100100
int: 100; hex: 0x64; oct: 0o144; bin: 0b1100100
100,000,000
1.00e+08
percentage: 33.33%
2020-06-18 19:36:38

References

  1. https://docs.python.org/3.8/library/string.html#format-string-syntax

  2. https://www.runoob.com/python/att-string-format.html

  3. https://stackoverflow.com/questions/1436703/difference-between-str-and-repr/1436756

  4. https://stackoverflow.com/questions/9196066/what-does-a-double-colon-followed-by-an-equals-sign-mean-in-programming-do

如果有收获,可以请我喝杯咖啡!