跳转至

Python 字符串格式化

概要: 如何在Python中优雅地格式化字符串

创建时间: 2022.11.08 22:32:35

更新时间: 2022.11.08 23:55:37

格式化字符串的三种方法

使用 %

提示

此写法带有 C 语言的 printf 风格,使用 % 对变量进行格式化输出和位置调整,这种格式化的风格称为 旧式的字符串格式化

示例

Python
1
2
3
4
name = 'Python'

print('Hello %s!' % name)
print('Hello %(name)s!' % {"name": name})
image.png
总结:这种方法写起来非常不 Pythonic,当需要输出的%多了的时候,会直接懵掉,虽然高版本Python依然支持,但不建议使用。

使用 format

提示

此写法调用了Python内置的 format 函数,支持在字符串内部通过尖括号对变量进行格式化和位置调整,详见 官网

Python
1
2
3
4
5
name = 'Python'
age = 31

print('Hello {}!'.format(name))
print('The {name:s} language is {age:d}'.format(name=name, age=age))
image.png
总结:这种方法比C语言风格好点,但第三种才是最优雅的方式。

使用 f-string

提示

Python 3.6+ 上,推荐使用几乎全能的 f-string 风格对字符串进行格式化输出,也称为格式字符串字面值。其基本用法是在需要格式化的字符串前面加 fF ,通过 {expression} 表达式,将表达式的值写入到字符串中。

基本用法示例

Python
import math
print(f'The value of pi is approximately {math.pi:.3f}.')
image.png
下面进行更为详细的用法举例

f-string的用法

利用表达式动态计算值输出

Python
print(f'2 * 2 = {2*2}')
image.png

利用Lambda表达式求值输出

不仅是 lambda ,实际上任何的函数都可以嵌套在 f-string 中使用

Python
1
2
3
4
5
def sq(x):
    return x * x

print(f'{sq(2)}')
print(f"{(lambda x: x**2)(3)}")
image.png

通过冒号设置最小字符串宽度进行列对齐

f-string 中,可以通过 : 符号进行类似表格的列宽限制的格式化输出

Python
1
2
3
table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
for name, phone in table.items():
    print(f'{name:10} ==> {phone:10d}')
image.png

格式化输出数字

Python
1
2
3
4
num = 123456789

print(f'{num:,}')  # 用 , 分割数字增强可读性
print(f'{num:012}')  # 对数字补零后输出
image.png

格式化日期时间

Python
1
2
3
4
5
import datetime

now = datetime.datetime.now()
print(f'date is {now:%Y-%m-%d}')
print(f'time is {now:%H:%M:%S}')
image.png

同时打印变量名和值

警告

需要 Python 3.8+

Python
x, y = 15, 27
print(f'{x = }, {y = }')
image.png

打印对象指定属性

提示

f-string 中,可以通过 '!s' 调用 str() 转换求值结果,'!r' 调用 repr(),'!a' 调用 ascii(),最终格式化结果使用 format() 函数的协议

Python
class Obj(object):
    def __init__(self):
        self.name = 'Python'
        self.age = 31

    def __str__(self):
        return f'My name is {self.name}, age is {self.age}'

    def __repr__(self):
        return f'name={self.name}, age={self.age}'


py = Obj()

print(f'{py}')
print(f'{repr(py)}')
print(f'{py!r}')

print(f'{str(py)}')
print(f'{py!s}')

s = '\n'
print(f'{s}')
print(f'{s!a}')
输出为
Text Only
1
2
3
4
5
6
7
8
My name is Python, age is 31
name=Python, age=31
name=Python, age=31
My name is Python, age is 31
My name is Python, age is 31


'\n'

参考