f`` 字符串(Python3.6+)类型与 format 函数的使用类似,但更简单。想要在字符串中插入变量的值,可在前引号(单引号/双引号)前加上字母 f
,再将要插入的变量放在花括号内。这样,当 Python 显示字符串时,将把每个变量都替换为其值。
这种字符串名为 f字符串
。f 是 format(设置格式) 的简写,因为 Python 通过把花括号内的变量替换为其值来设置字符串的格式。
>>> name = 'Alex'
>>> age = 25
>>> sex = 'Male'
>>> introducation = 'My name is {name},I am a {sex},and I am {age} years old.'.format(name=name,sex=sex,age=age)
>>> introducation
'My name is Alex,I am a boy,and I am 25 years old.'
>>> introducation = f'My name is {name},I am a {sex},and I am {age} years old.'
>>> introducation
'My name is Alex,I am a boy,and I am 25 years old.'
>>> info = {'name': 'Alex', 'age': 25, 'sex': 'boy'}
>>> introducation = f'My name is {info["name"]},I am a {info["sex"]},and I am {info["age"]} years old.'
>>> introducation
'My name is Alex,I am a boy,and I am 25 years old.'