f-string
格式化字符串常量(formatted string literals),是Python3.6新引入的一种字符串格式化方法,该方法源于PEP 498 – Literal String Interpolation
,主要目的是使格式化字符串的操作更加简便
。f-string在形式上是以 f 或 F 修饰符引领的字符串(f'xxx' 或 F'xxx')
,以大括号 {}
标明被替换的字段;f-string在本质上并不是字符串常量
,而是一个在运行时运算求值的表达式
:
f-string在功能方面不逊于传统的%-formatting语句和str.format()函数
,同时性能又优于二者,且使用起来也更加简洁明了,因此对于Python3.6及以后的版本,推荐使用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-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."
自定义格式:对齐、宽度、符号、补零、精度、进制等
f-string采用 {content:format}
设置字符串格式,其中 content
是替换并填入字符串的内容
,可以是变量
、表达式或函数
等,format 是格式描述符
。采用默认
格式时不必指定 {:format}
,如上面例子所示只写 {content}
即可。