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

时间:2016-05-03 22:31:38

标签: python variables quotes

帮助我无法使其工作,我试图将变量age放入字符串中,但它不会正确加载变量。

这是我的代码:

import random
import sys
import os


age = 17
print(age)
quote = "You are" age "years old!"

给出了这个错误:

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

Process finished with exit code 1

3 个答案:

答案 0 :(得分:9)

您应该在此处使用字符串格式化程序或连接。要进行连接,您必须将int转换为string。您不能将整数和字符串连接在一起。

如果你尝试这会引发以下错误:

TypeError: unsupported operand type(s) for +: 'int' and 'str'

格式:

quote = "You are %d years old" % age
quote = "You are {} years old".format(age)

连接(单向)

quote = "You are " + str(age) + " years old" 

编辑:正如J.F. Sebastian在评论中所述,我们也可以做以下事情

在Python 3.6中:

f"You are {age} years old"

早期版本的Python:

"You are {age} years old".format(**vars())

答案 1 :(得分:0)

这是一种方法:

>>> age = 17
>>> quote = "You are %d years old!" % age
>>> quote
'You are 17 years old!'
>>> 

答案 2 :(得分:0)

您需要使用+符号将其插入字符串中,如下所示:

quote = "You are " + age + " years old!"

您可以在Python's string documentation上了解有关其他方法的更多信息。