Python格式化字符串f-string

f-string,亦称为格式化字符串常量(formatted string literals),是Python3.6新引入的一种字符串格式化方法,该方法源于PEP 498 – Literal String Interpolation,主要目的是使格式化字符串的操作更加简便。f-string在形式上是以 f 或 F 修饰符引领的字符串(f'xxx' 或 F'xxx'),以大括号 {} 标明被替换的字段;f-string在本质上并不是字符串常量,而是一个在运行时运算求值的表达式:

While other string literals always have a constant value, formatted strings are really expressions evaluated at run time.
(与具有恒定值的其它字符串常量不同,格式化字符串实际上是运行时运算求值的表达式。)
—— Python Documentation

f-string在功能方面不逊于传统的%-formatting语句和str.format()函数,同时性能又优于二者,且使用起来也更加简洁明了,因此对于Python3.6及以后的版本,推荐使用f-string进行字符串格式化。

用法

此部分内容主要参考以下资料:

Python Documentation – Formatted String Literals
Python Documentation – Format String Syntax
PEP 498 – Literal String Interpolation
Python 3’s f-Strings: An Improved String Formatting Syntax (Guide)
python3 f-string格式化字符串的高级用法
Python 3: An Intro to f-strings

简单使用
f-string用大括号 {} 表示被替换字段,其中直接填入替换内容:

>>> name = 'Eric'
>>> f'Hello, my name is {name}'
'Hello, my name is Eric'

>>> number = 7
>>> f'My lucky number is {number}'
'My lucky number is 7'

>>> price = 19.99
>>> f'The price of this book is {price}'
'The price of this book is 19.99'

表达式求值与函数调用

f-string的大括号 {} 可以填入表达式或调用函数,Python会求出其结果并填入返回的字符串内:

>>> f'A total number of {24 * 8 + 4}'
'A total number of 196'

>>> f'Complex number {(2 + 2j) / (2 - 3j)}'
'Complex number (-0.15384615384615388+0.7692307692307692j)'

>>> name = 'ERIC'
>>> f'My name is {name.lower()}'
'My name is eric'

>>> import math
>>> f'The answer is {math.log(math.pi)}'
'The answer is 1.1447298858494002'

引号、大括号与反斜杠
f-string大括号内所用的引号不能和大括号外的引号定界符冲突,可根据情况灵活切换 ' 和 ":

>>> f'I am {"Eric"}'
'I am Eric'
>>> f'I am {'Eric'}'
  File "", line 1
    f'I am {'Eric'}'
                ^
SyntaxError: invalid syntax

若 ' 和 " 不足以满足要求,还可以使用 ''' 和 """:

>>> f"He said {"I'm Eric"}"
  File "", line 1
    f"He said {"I'm Eric"}"
                ^
SyntaxError: invalid syntax

>>> f'He said {"I'm Eric"}'
  File "", line 1
    f'He said {"I'm Eric"}'
                  ^
SyntaxError: invalid syntax

>>> f"""He said {"I'm Eric"}"""
"He said I'm Eric"
>>> f'''He said {"I'm Eric"}'''
"He said I'm Eric"

大括号外的引号还可以使用 \ 转义,但大括号内不能使用 \ 转义:

>>> f'''He\'ll say {"I'm Eric"}'''
"He'll say I'm Eric"
>>> f'''He'll say {"I\'m Eric"}'''
  File "", line 1
SyntaxError: f-string expression part cannot include a backslash

f-string大括号外如果需要显示大括号,则应输入连续两个大括号 {{ 和 }}:

>>> f'5 {"{stars}"}'
'5 {stars}'
>>> f'{{5}} {"stars"}'
'{5} stars'

上面提到,f-string大括号内不能使用 \ 转义,事实上不仅如此,f-string大括号内根本就不允许出现 \。如果确实需要 \,则应首先将包含 \ 的内容用一个变量表示,再在f-string大括号内填入变量名:

>>> f"newline: {ord('\n')}"
  File "", line 1
SyntaxError: f-string expression part cannot include a backslash

>>> newline = ord('\n')
>>> f'newline: {newline}'
'newline: 10'

多行f-string
f-string还可用于多行字符串:

>>> name = 'Eric'
>>> age = 27
>>> f"Hello!" \
... f"I'm {name}." \
... f"I'm {age}."
"Hello!I'm Eric.I'm 27."
>>> f"""Hello!
...     I'm {name}.
...     I'm {age}."""
"Hello!\n    I'm Eric.\n    I'm 27."

lambda表达式

f-string大括号内也可填入lambda表达式,但lambda表达式的 : 会被f-string误认为是表达式与格式描述符之间的分隔符,为避免歧义,需要将lambda表达式置于括号 () 内:

>>> f'result is {lambda x: x ** 2 + 1 (2)}'
  File "", line 1
    (lambda x)
             ^
SyntaxError: unexpected EOF while parsing

>>> f'result is {(lambda x: x ** 2 + 1) (2)}'
'result is 5'
>>> f'result is {(lambda x: x ** 2 + 1) (2):<+7.2f}'
'result is +5.00  '
image.png

更多例子:
'f-strings’是Python的一种新的字符串格式化方法,要使用f-strings,只需在字符串前加上f。
基本用法

name = "Tom"
age = 3
f"His name is {name}, he's {age} years old."
"His name is Tom, he's 3 years old."

实质上,把括号内的当作是变量即可。
支持表达式

数学运算

f'He will be { age+1 } years old next year.'
'He will be 4 years old next year.'

对象操作

spurs = {"Guard": "Parker", "Forward": "Duncan"}
f"The {len(spurs)} players are: {spurs['Guard']} the guard, and {spurs['Forward']} the forward."
'The 2 players are: Parker the guard, and Duncan the forward.'

f'Numbers from 1-10 are {[_ for _ in range(1, 11)]}'
'Numbers from 1-10 are [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]'

数字操作

# 小数精度
PI = 3.141592653
f"Pi is {PI:.2f}"
'Pi is 3.14'

# 进制转换
f'int: 31, hex: {31:x}, oct: {31:o}'
'int: 31, hex: 1f, oct: 37'

与原始字符串联合使用(使其没有转义字符)

fr'hello\nworld'
'hello\\nworld'

注意事项
{}内不能包含反斜杠\,但可以使用不同的引号,或使用三引号。使用引号是将不再表示一个变量,而是当作了字符串来处理。
如何插入大括号?

f"{{ {10 * 8} }}"
'{ 80 }'
f"{{ 10 * 8 }}"
'{ 10 * 8 }'

使用str.format(),非数字索引将自动转化为字符串,而f-strings则不会

"Guard is {spurs[Guard]}".format(spurs=spurs)
'Guard is Parker'

f"Guard is {spurs[Guard]}"
Traceback (most recent call last):
  File "", line 1, in 
    f"Guard is {spurs[Guard]}"
NameError: name 'Guard' is not defined

f"Guard is {spurs['Guard']}"
'Guard is Parker'

摘自:
原文链接:https://blog.csdn.net/sunxb10/article/details/81036693
原文链接:https://blog.csdn.net/qq_29027865/article/details/84850683

你可能感兴趣的:(Python格式化字符串f-string)