将变量放入字符串(引用)

Tim*_*Tim 7 python variables quotes

帮助我不能让它工作,我试图将变量年龄放入字符串但它不会正确加载变量.

这是我的代码:

import random
import sys
import os


age = 17
print(age)
quote = "You are" age "years old!"
Run Code Online (Sandbox Code Playgroud)

给出了这个错误:

File "C:/Users/----/PycharmProjects/hellophyton/hellophyton.py", line 9
        quote = "You are" age "years old!"
                        ^
SyntaxError: invalid syntax

Process finished with exit code 1
Run Code Online (Sandbox Code Playgroud)

Pyt*_*sta 13

您应该在此处使用字符串格式化程序或连接.对于连接,您必须将inta 转换为a string.您不能将整数和字符串连接在一起.

如果您尝试,这将引发以下错误:

TypeError: unsupported operand type(s) for +: 'int' and 'str'
Run Code Online (Sandbox Code Playgroud)

格式:

quote = "You are %d years old" % age
quote = "You are {} years old".format(age)
Run Code Online (Sandbox Code Playgroud)

连接(单向)

quote = "You are " + str(age) + " years old" 
Run Code Online (Sandbox Code Playgroud)

编辑:正如JF Sebastian在评论中指出的那样,我们也可以做到以下几点

在Python 3.6中:

f"You are {age} years old"
Run Code Online (Sandbox Code Playgroud)

早期版本的Python:

"You are {age} years old".format(**vars())
Run Code Online (Sandbox Code Playgroud)

  • 在早期的Python版本中提到`f"你是{age}岁"在Python 3.6或`"你是{age}岁".format(**vars())` (2认同)