一、简单例子
name = 'xingzhe007'
age = 29
f"Hello, {name}. you are {age}"
-- > 'Hello, xingzhe007. you are 29'
二、任意表达式
-
f字符串
是在运行时进行渲染,因此可以将任何有效的Python表达式放入其中;f"{2*26}" --> '52' f"{name.lower()} is funny." --> 'xingzhe007 is funny.'
- 可以使用带有
f字符串
的类创建对象。class f_str: def __init__(self, name, age, sex): self.name = name self.age = age self.sex = sex def __repr__(self): return f"your name is {self.name}, and age is {self.age}, but you are {self.sex}, Surprise!" you_self = f_str("xingzhe", 29, "male") you_self --> Your name is xingzhe, and age is 29, but you are male, Surprise!
三、多行 f-string
- 每一行开头放一个
f
;profession = "comedian" affiliation = "Monty Python" message = (f"Hi {name}. " f"You are a {profession}. " f"You were in {affiliation}.") message --> 'Hi xingzhe007. You are a comedian. You were in Monty Python.'
- 某一行放个
f
,仅该行进行匹配,其它行不变;message = (f"Hi {name}. " "You are a {profession}. " "You were in {affiliation}.") message --> 'Hi xingzhe007. You are a {profession}. You were in {affiliation}.'
- 多行一个
f
且使用三个引号时,返回时有换行符。message = f""" Hi {name}. You are a {profession}. You were in {affiliation}. """ message --> '\n Hi xingzhe007. \n You are a comedian. \n You were in Monty Python.\n '
四、使用细节
-
引号
: 在表达式中可以使用各种类型的引号,需确保在表达式中使用的f-字符串外部没有使用相同类型的引号即可; -
字典
: 字典的键
使用单引号时,需确保包含键
的f字符串使用双引号; -
大括号
: 为了使字符串出现大括号,必须使用双大括号; -
反斜杠
:f
字符串的字符串部分
可以使用反斜杠转义,但是,不能在表达式部分
使用反斜杠进行转义; -
lambda表达式
: 如果!
/:
/}
不在括号、大括号、或字符串中,则它将被解释为表达式的结尾。由于lambda使用:
,会导致一些报错,解决办法:将lambda表达式嵌套在圆括号中。f"{(lambda x: x * 37) (2)}" --> '74'
6.不能与'u'
联合使用:'u'
是为了与Python2.7兼容的,而Python2.7不会支持f-strings,因此与'u'
联合使用不会有任何效果