{% raw %}
Python f 字符串教程
Python f 字符串教程显示了如何使用 f 字符串在 Python 中格式化字符串。
Python f 字符串
Python f 字符串是执行字符串格式化的最新 Python 语法。 自 Python 3.6 起可用。 Python f 字符串提供了一种更快,更易读,更简明且不易出错的在 Python 中格式化字符串的方式。
f 字符串的前缀为f,并使用{}括号求值值。
在冒号后指定用于类型,填充或对齐的格式说明符; 例如:f'{price:.3}',其中price是变量名。
Python 字符串格式
以下示例总结了 Python 中的字符串格式设置选项。
formatting_strings.py
#!/usr/bin/env python3name = 'Peter'age = 23print('%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))
从 Python 3.0 开始,format()函数被引入以提供高级格式化选项。
print(f'{name} is {age} years old')
从 Python 3.6 开始,Python f 字符串可用。 该字符串具有f前缀,并使用{}求值变量。
$ python formatting_string.pyPeter is 23 years oldPeter is 23 years oldPeter is 23 years old
我们有相同的输出。
Python f 字符串表达式
我们可以将表达式放在{}括号之间。
expressions.py
#!/usr/bin/env python3bags = 3apples_in_bag = 12print(f'There are total of {bags * apples_in_bag} apples')
该示例对 f 字符串中的表达式求值。
$ python expressions.pyThere are total of 36 apples
这是输出。
Python f 字符串字典
我们可以使用 f 字符串中的字典。
dicts.py
#!/usr/bin/env python3user = {'name': 'John Doe', 'occupation': 'gardener'}print(f"{user['name']} is a {user['occupation']}")
该示例以 f 字符串形式求值字典。
$ python dicts.pyJohn Doe is a gardener
这是输出。
Python 多行 f 字符串
我们可以使用多行字符串。
multiline.py
#!/usr/bin/env python3name = 'John Doe'age = 32occupation = 'gardener'msg = (f'Name: {name}\n'f'Age: {age}\n'f'Occupation: {occupation}')print(msg)
该示例显示了多行 f 字符串。 F 字符串放在方括号之间; 每个字符串前面都带有f字符。
$ python multiline.pyName: John DoeAge: 32Occupation: gardener
这是输出。
Python f 字符串调用函数
我们还可以在 f 字符串中调用函数。
call_function.py
#!/usr/bin/env python3def mymax(x, y):return x if x > y else ya = 3b = 4print(f'Max of {a} and {b} is {mymax(a, b)}')
该示例在 f 字符串中调用自定义函数。
$ python call_fun.pyMax of 3 and 4 is 4
这是输出。
Python f 字符串对象
Python f 字符串也接受对象。 对象必须定义了__str__()或__repr__()魔术函数。
objects.py
#!/usr/bin/env python3class User:def __init__(self, name, occupation):self.name = nameself.occupation = occupationdef __repr__(self):return f"{self.name} is a {self.occupation}"u = User('John Doe', 'gardener')print(f'{u}')
该示例求值 f 字符串中的对象。
$ python objects.pyJohn Doe is a gardener
这是输出。
Python F 字符串转义字符
下面的示例显示如何对 f 字符串中的某些字符进行转义。
escaping.py
#!/usr/bin/env python3print(f'Python uses {{}} to evaludate variables in f-strings')print(f'This was a \'great\' film')
为了避免花括号,我们将字符加倍。 单引号以反斜杠字符转义。
$ python escaping.pyPython uses {} to evaludate variables in f-stringsThis was a 'great' film
这是输出。
Python f 字符串格式化日期时间
以下示例格式化日期时间。
format_datetime.py
#!/usr/bin/env python3import datetimenow = datetime.datetime.now()print(f'{now:%Y-%m-%d %H:%M}')
该示例显示格式化的当前日期时间。 日期时间格式说明符位于:字符之后。
$ python format_datetime.py2019-05-11 22:39
这是输出。
Python f 字符串格式化浮点数
浮点值的后缀为f。 我们还可以指定精度:小数位数。 精度是一个点字符后的值。
format_floats.py
#!/usr/bin/env python3val = 12.3print(f'{val:.2f}')print(f'{val:.5f}')
该示例打印格式化的浮点值。
$ python format_floats.py12.3012.30000
输出显示具有两位和五个小数位的数字。
Python f 字符串格式化宽度
宽度说明符设置值的宽度。 如果该值短于指定的宽度,则该值可以用空格或其他字符填充。
format_width.py
#!/usr/bin/env python3for x in range(1, 11):print(f'{x:02} {x*x:3} {x*x*x:4}')
该示例打印三列。 每个列都有一个预定义的宽度。 第一列使用 0 填充较短的值。
$ python format_width.py01 1 102 4 803 9 2704 16 6405 25 12506 36 21607 49 34308 64 51209 81 72910 100 1000
这是输出。
Python f 字符串对齐字符串
默认情况下,字符串在左边对齐。 我们可以使用>字符来对齐右侧的字符串。 >字符在冒号后面。
justify.py
#!/usr/bin/env python3s1 = '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.pyaababcabcd
这是输出。
Python f 字符串数字符号
数字可以具有各种数字符号,例如十进制或十六进制。
format_notations.py
#!/usr/bin/env python3a = 300# hexadecimalprint(f"{a:x}")# octalprint(f"{a:o}")# scientificprint(f"{a:e}")
该示例以三种不同的表示法打印值。
$ python format_notations.py12c4543.000000e+02
这是输出。
在本教程中,我们使用了 Python f 字符串。
您可能也对以下相关教程感兴趣: Python 字符串, Python Jinja 教程和 Python 教程,或列出所有 Python 教程。
{% endraw %}
