Python中的 f-string用法.
Python f-string是执行字符串格式化的最新Python语法。 自Python 3.6起可用。 Python f字符串提供了一种更快,更易读,更简明且不易出错的在Python中格式化字符串的方式。
f-string带有f前缀,并使用{}花括号来评估值.
在冒号后面指定用于类型,填充或对齐的格式说明符; 例如:f'{price:.3}',其中price是变量名。
Python字符串格式化
我们先新建一个formatting_strings.py文件,写入:
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')
执行结果为:
Peter is 23 years old
Peter is 23 years old
Peter is 23 years old
三条打印结果是等效的。
Python f-string表达式,新建一个expressions.py文件:写入:
bags = 3
apples_in_bag = 12
print(f'There are total of {bags * apples_in_bag} apples')
输出为:
There are total of 36 apples
Python f-string字典,新建一个dicts.py文件,写入:
user = {'name': 'John Doe', 'occupation': 'gardener'}
print(f"{user['name']} is a {user['occupation']}")
结果为:
John Doe is a gardener
Python多行 f-string,新建一个multiline.py文件,写入:
name = 'John Doe'
age = 32
occupation = 'gardener'
msg = (
f'Name: {name}\n'
f'Age: {age}\n'
f'Occupation: {occupation}'
)
print(msg)
执行结果为:
Name: John Doe
Age: 32
Occupation: gardener
Python f-string 调用函数,新建一个call_function.py文件,写入:
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)}')
执行结果为:
Max of 3 and 4 is 4
Python f-string 对象,新建一个objects.py文件,写入:
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}')
执行结果:
John Doe is a gardener
Python f-string 转义字符,新建一个escaping.py文件,写入:
print(f'Python uses {{}} to evaludate variables in f-strings')
print(f'This was a \'great\' film')
执行结果为:
Python uses {} to evaludate variables in f-strings
This was a 'great' film
Python f-string中的日期时间格式化,新建一个format_datetime.py文件,写入:
import datetime
now = datetime.datetime.now()
print(f'{now:%Y-%m-%d %H:%M}')
输出结果为:
2020-04-29 22:39
Python f-string 中格式化浮点数,新建一个format_floats.py文件,写入:
val = 12.3
print(f'{val:.2f}')
print(f'{val:.5f}')
输出结果为:
12.30
12.30000
Python f-string 格式化宽度,新建一个format_width.py文件,写入:
for x in range(1, 11):
print(f'{x:02} {x*x:3} {x*x*x:4}')
输出结果为:
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文件,写入:
s1 = 'a'
s2 = 'ab'
s3 = 'abc'
s4 = 'abcd'
print(f'{s1:>10}')
print(f'{s2:>10}')
print(f'{s3:>10}')
print(f'{s4:>10}')
输出结果为:
a
ab
abc
abcd
Python f-string中的数字符号,新建一个format_notations.py文件,写入:
a = 300
# 十六进制
print(f"{a:x}")
# 八进制
print(f"{a:o}")
#科学计数法
print(f"{a:e}")
输出结果为:
12c
454
3.000000e+02
希望对大家有用,欢迎阅读与转发,谢谢!