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