Pythonf-string教程展示了如何使用f-string在Python中格式化字符串。
Pythonf字符串
Pythonf-string是进行字符串格式化的最新Python语法。它从Python3.6开始可用。Pythonf字符串提供了一种在Python中格式化字符串的更快、更易读、更简洁且不易出错的方法。
f字符串具有f前缀并使用{}括号来计算值。
类型、填充或对齐的格式说明符在冒号字符之后指定;例如:f'{price:.3}',其中price是一个变量名。
Python字符串格式化
以下示例总结了Python中的字符串格式化选项。
#!/usr/bin/python
name = 'Peter'
age = 23
print('%s is %d years old' % (name, age))
print('{} is {} years old'.format(name, age))
print(f'{name} is {age} years old')
该示例使用两个变量格式化字符串。
print('%s is %d years old' % (name, age))
这是最早的选项。它使用%运算符和经典字符串格式指定,例如%s和%d。
print('{} is {} years old'.format(name, age))
自Python3.0起,引入了format函数以提供高级格式化选项。
print(f'{name} is {age} years old')
Pythonf字符串从Python3.6开始可用。该字符串具有f前缀并使用{}评估变量。
$ python formatting_string.py Peter is 23 years old Peter is 23 years old Peter is 23 years old
Pythonf字符串表达式
我们可以将表达式放在{}括号之间。
#!/usr/bin/python
bags = 3
apples_in_bag = 12
print(f'There are total of {bags * apples_in_bag} apples')
该示例计算f字符串中的表达式。
$ python expressions.py There are total of 36 apples
Pythonf字符串字典
我们可以在f字符串中使用字典。
#!/usr/bin/python
user = {'name': 'John Doe', 'occupation': 'gardener'}
print(f"{user['name']} is a {user['occupation']}")
该示例评估f字符串中的字典。
$ python dicts.py John Doe is a gardener
Pythonf字符串调试
Python3.8引入了带有=字符的自记录表达式。
#!/usr/bin/python
import math
x = 0.8
print(f'{math.cos(x) = }')
print(f'{math.sin(x) = }')
该示例在调试模式下输出正弦和余弦函数。
$ python debug.py math.cos(x) = 0.6967067093471654 math.sin(x) = 0.7173560908995228
Python多行f字符串
我们可以使用多行字符串。
#!/usr/bin/python
name = 'John Doe'
age = 32
occupation = 'gardener'
msg = (
f'Name: {name}\n'
f'Age: {age}\n'
f'Occupation: {occupation}'
)
print(msg)
这个例子展示了一个多行的f字符串。f弦放在圆括号之间;每个字符串前面都有f字符。
$ python multiline.py Name: John Doe Age: 32 Occupation: gardener
Pythonf-string调用函数
我们也可以在f字符串中调用函数。
#!/usr/bin/python
def mymax(x, y):
return x if x > y else y
a = 3
b = 4
print(f'Max of {a} and {b} is {mymax(a, b)}')
该示例调用f字符串中的自定义函数。
$ python call_fun.py Max of 3 and 4 is 4
Pythonf字符串对象
Pythonf-string也接受对象;对象必须定义__str__或__repr__魔法函数。
#!/usr/bin/python
class User:
def __init__(self, name, occupation):
self.name = name
self.occupation = occupation
def __repr__(self):
return f"{self.name} is a {self.occupation}"
u = User('John Doe', 'gardener')
print(f'{u}')
该示例评估f字符串中的对象。
$ python objects.py John Doe is a gardener
Pythonf字符串转义字符
以下示例显示如何转义f字符串中的某些字符。
#!/usr/bin/python
print(f'Python uses {{}} to evaludate variables in f-strings')
print(f'This was a \'great\' film')
为了转义大括号,我们将字符加倍。单引号用反斜杠字符转义。
$ python escaping.py
Python uses {} to evaludate variables in f-strings
This was a 'great' film
Pythonf-string格式化日期时间
以下示例格式化日期时间。
#!/usr/bin/python
import datetime
now = datetime.datetime.now()
print(f'{now:%Y-%m-%d %H:%M}')
该示例显示格式化的当前日期时间。日期时间格式说明符跟在:字符之后。
$ python format_datetime.py 2021-08-20 15:13
Pythonf字符串格式浮点数
浮点值有f后缀。我们还可以指定精度:小数位数。精度是紧跟在点字符之后的值。
#!/usr/bin/python
val = 12.3
print(f'{val:.2f}')
print(f'{val:.5f}')
该示例打印格式化的浮点值。
$ python format_floats.py 12.30 12.30000
输出显示具有两位和五位小数的数字。
Pythonf-string格式宽度
宽度说明符设置值的宽度。如果该值小于指定宽度,则该值可能会被空格或其他字符填充。
#!/usr/bin/python
for x in range(1, 11):
print(f'{x:02} {x*x:3} {x*x*x:4}')
该示例打印三列。每列都有预定义的宽度。第一列使用0来填充较短的值。
$ python format_width.py 01 1 1 02 4 8 03 9 27 04 16 64 05 25 125 06 36 216 07 49 343 08 64 512 09 81 729 10 100 1000
Pythonf-string对齐字符串
默认情况下,字符串向左对齐。我们可以使用>字符将字符串右对齐。>字符跟在冒号字符之后。
#!/usr/bin/python
s1 = 'a'
s2 = 'ab'
s3 = 'abc'
s4 = 'abcd'
print(f'{s1:>10}')
print(f'{s2:>10}')
print(f'{s3:>10}')
print(f'{s4:>10}')
我们有四个不同长度的字符串。我们将输出的宽度设置为十个字符。这些值右对齐。
$ python justify.py
a
ab
abc
abcd
Pythonf字符串数字符号
数字可以有各种数字表示法,例如十进制或十六进制。
#!/usr/bin/python
a = 300
# hexadecimal
print(f"{a:x}")
# octal
print(f"{a:o}")
# scientific
print(f"{a:e}")
该示例以三种不同的表示法打印一个值。
$ python format_notations.py 12c 454 3.000000e+02
在本教程中,我们使用了Pythonf字符串。
访问Python教程或列出所有Python教程。
