python格式化字符串

%-formatting

使用

1
2
name = "Eric"
"Hello, %s." % name

插入多个变量需要元组

“Hello, %s. You are %s.” % (name, age)

这种格式不是很好,因为它是冗长的,会导致错误,比如不能正确显示元组或字典

str.format()

这种更新的工作方式是在Python 2.6中引入的

使用

1
"Hello, {}. You are {}.".format(name, age)

可以使用字典

1
2
person = {'name': 'Eric', 'age': 74}
"Hello, {name}. You are {age}.".format(**person)

使用str.format()的代码比使用%-formatting的代码更易读,但当处理多个参数和更长的字符串时,str.format()仍然可能非常冗长

f-Strings

f-Strings也称为“格式化字符串文字”,F字符串是开头有一个f的字符串文字,以及包含表达式的大括号将被其值替换。表达式在运行时进行渲染,然后使用__format__协议进行格式化。在python3.6中引入.

使用

1
2
3
name = "Tom"
age = 74
f"Hello, {name}. You are {age}."