为什么不允许将字符串作为值嵌入到 f 字符串中?
Why aren't strings allowed to be embedded into f-strings just as values?
print(f"my age is {54} and my name is {True}")
产量
my age is 54 and my name is True
以下也有效
print(f"my age is {54.0} and my name is {True}")
但是,当我将字符串放在大括号内时:
print(f"my age is {54.0} and my name is {"Bill"}")
我收到无效语法错误。
那么在此实例中,字符串数据类型与其他基元有何不同?
没什么不同,您只需要对 f 字符串本身和占位符内的字符串使用不同类型的引号即可:
print(f'my age is {54.0} and my name is {"Bill"}')
您甚至可以使用不同的引号字符嵌套 f 字符串:
print(f'{f"{123}"}')
print(f"my age is {54} and my name is {True}")
产量
my age is 54 and my name is True
以下也有效
print(f"my age is {54.0} and my name is {True}")
但是,当我将字符串放在大括号内时:
print(f"my age is {54.0} and my name is {"Bill"}")
我收到无效语法错误。
那么在此实例中,字符串数据类型与其他基元有何不同?
没什么不同,您只需要对 f 字符串本身和占位符内的字符串使用不同类型的引号即可:
print(f'my age is {54.0} and my name is {"Bill"}')
您甚至可以使用不同的引号字符嵌套 f 字符串:
print(f'{f"{123}"}')