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
3name = "Jack"
age = 20
'hello, %s, %d' % (name, age)基于字典的格式化
1
2
3n = "Jack"
a = 20
'hello, %(name)s, %(age)d' % {'name': n, 'age': a}
2. str.format(...)
Example 1
1 | >>> '{0}, {1}, {2}'.format('a', 'b', 'c') |
Example 2
1 | >>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W') |
Example 3
1 | 'Point({self.x}, {self.y})'.format(self=self) |
Example 4
1 | >>> '{:<30}'.format('left aligned') |
Example 5
1 | >>> '{:,}'.format(1234567890) |
Example 6
1 | >>> import datetime |
Example 7
1 | >>> points = 19 |
Example 8
1 | count = 100 |
3. f-string
f-string
实际是 str.format(...)
的简写形式,可以直接在字符串中进行插值变量,而无需以参数的形式显式传递给某个格式化
函数。
文档: https://docs.python.org/3/tutorial/inputoutput.html#formatted-string-literals
示例:
1 | r = 2.5 |