他的结构就是F+str 或者 f+str的形式,在字符串中想替换的位置用{}展位,与format类似,但是用在字符串后面写入替换的内容,而他可以直接识别
name = '小旋风' age = 18 sex = '男' msg = F'姓名:{name},性别:{age},年龄:{sex}' # 大写字母也可以 msg = f'姓名:{name},性别:{age},年龄:{sex}' print(msg) ''' 输出结果: 姓名:小旋风,性别:18,年龄:男 '''
可以添加任何表达式:
print(f'{3*21}') # 63 name ='xiao' print(f"全部大写:{name.upper()}") # 全部大写:XIAO # 字典也可以 teacher = {'name': '小旋风', 'age': 18} msg = f"The teacher is {teacher['name']}, aged {teacher['age']}" print(msg) # The comedian is 小旋风, aged 18 # 列表也行 l1 = ['小旋风', 18] msg = f'姓名:{l1[0]},年龄:{l1[1]}.' print(msg) # 姓名:小旋风,年龄:18.
def sum_a_b(a,b): return a + b a = 1 b = 2 print('求和的结果为' + f'{sum_a_b(a,b)}')