What I Learnt Today 2022-01-23

Python 字符串格式化的三种方法

1. % 操作符

文档: https://docs.python.org/3.9/library/stdtypes.html?highlight=str#printf-style-string-formatting

  • 普通的字符串格式化

    1
    2
    3
    name = "Jack"
    age = 20
    'hello, %s, %d' % (name, age)
  • 基于字典的格式化

    1
    2
    3
    n = "Jack"
    a = 20
    'hello, %(name)s, %(age)d' % {'name': n, 'age': a}

2. str.format(...)

Example 1

1
2
3
4
5
6
>>> '{0}, {1}, {2}'.format('a', 'b', 'c')
'a, b, c'
>>> '{}, {}, {}'.format('a', 'b', 'c') # 3.1+ only
'a, b, c'
>>> '{2}, {1}, {0}'.format('a', 'b', 'c')
'c, b, a'

Example 2

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

Example 3

1
2
3
4
'Point({self.x}, {self.y})'.format(self=self)

coord = (3, 5)
'X: {0[0]}; Y: {0[1]}'.format(coord)

Example 4

1
2
3
4
>>> '{:<30}'.format('left aligned')
'left aligned '
>>> '{:>30}'.format('right aligned')
' right aligned'

Example 5

1
2
>>> '{:,}'.format(1234567890)
'1,234,567,890'

Example 6

1
2
3
4
>>> import datetime
>>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)
>>> '{:%Y-%m-%d %H:%M:%S}'.format(d)
'2010-07-04 12:15:58'

Example 7

1
2
3
4
>>> points = 19
>>> total = 22
>>> 'Correct answers: {:.2%}'.format(points/total)
'Correct answers: 86.36%'

Example 8

1
2
count = 100
'Count: {:04d}'.format(count) # ==> "Count: 0100"

3. f-string

f-string 实际是 str.format(...) 的简写形式,可以直接在字符串中进行插值变量,而无需以参数的形式显式传递给某个格式化 函数。

文档: https://docs.python.org/3/tutorial/inputoutput.html#formatted-string-literals

示例:

1
2
3
r = 2.5
s = 3.14 * r ** 2
f'The area of a circle with radius {r} is {s:.2f}' # => The area of a circle with radius 2.5 is 19.62
Powered By Valine
v1.5.2