Python f-string¶
本文展示如何通过f-string格式化字符串。
Python f-string 实用小片段¶
Python f-string是Python字符串格式化的最新语法。从Python3.6开始可用。在Python语言中,它提供了一种更快、可读性更好、更简洁、更不易出错的字符串格式化方法。
f-strings使用 f
前缀与花括号 {}
来格式化字符串。
类型、填充或者对齐等格式指示符在冒号后指定,例如f'{price:.3}'
,price是变量名。
Python字符串格式化¶
以下例子总结了Pyhton里可用的字符串格式化选项。
formatting_strings.py
例子使用两个变量格式化字符串。
#!/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')
python formatting_string.pyPeter is 23 years old
Peter is 23 years old
Peter is 23 years old
Peter is 23 years old
Peter is 23 years old
Python f-string表达式¶
花括号{ }
中可以使用表达式。
expressions.py
f-string内的表达式会自动计算。
#!/usr/bin/python
bags = 3
apples_in_bag = 12
print(f'There are total of {bags * apples_in_bag} apples')
Python f-string 字典¶
字典在f-strings内仍然起作用。
dicts.py
f-string内的字典会自动进行取值操作。
#!/usr/bin/python
user = {'name': 'John Doe', 'occupation': 'gardener'}
print(f"{user['name']} is a {user['occupation']}")
Python f-string debug¶
Python 3.8 通过 =
符号在f-string内引入了自文档表达式。
Python 多行 f-string¶
f-string的多行模式。
multiline.py
例子展示了一个多行f-string。在圆括号内放置多行f-string;每一行字符串都以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)
Python f-string 调用函数¶
f-strings内也可以调用函数。
call_function.py
在f-string内调用了一个自定义函数。
#!/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)}')
Python f-string对象¶
Python f-string也可以接受对象;接收的对象必须在内部实现__str__
或__repr__
函数。
objects.py
在f-string内会自动求值对象的字符串输出。
#!/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}')
Python f-string 转义字符¶
以下例子展示如何在f-string内转义特定字符。
escaping.py
要输出花括号,请输入两次花括号。单引号使用反斜杠转义。
#!/usr/bin/python
print(f'Python uses {{}} to evaludate variables in f-strings')
print(f'This was a \'great\' film')
Python f-string 格式化日期时间¶
以下例子格式化日期时间。
format_datetime.py
例子中打印一个格式化的日期时间。日期时间格式化指示符位于冒号:之后。
#!/usr/bin/python
import datetime
now = datetime.datetime.now()
print(f'{now:%Y-%m-%d %H:%M}')
Python f-string 格式化浮点数¶
浮点数带f后缀。也可以指定精度:小数点后位数。精度由点号.
后跟着的数字决定。
从输出可以看到小数位分别为2和5位。
Python f-string 格式化宽度¶
宽度指示符设置输出的宽度。如果输出数值小于指定宽度,前面由空格或其他字符填充。
本例输出3列数值,每列有指定宽度。第一列使用0填充不足2位的数据。$ 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
Python f-string 对齐字符串¶
默认的对齐方式是左对齐。可以使用 >
符号指定右对齐。>
符号紧跟于冒号之后。
justify.py
这里有4行不同长字符串。我们设置输出宽度为10,右对齐。
#!/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 f-string 数值表示法¶
数值有不同的表示方法,比如10进制或16进制。
format_notations.py
这里输出了一个数值的3种不同进制
#!/usr/bin/python
a = 300
# hexadecimal
print(f"{a:x}")
# octal
print(f"{a:o}")
# scientific
print(f"{a:e}")
在本文中,我们简单的学习了f-string。