将变量放入字符串(引号)
发布于 2021-01-29 16:00:34
帮助我无法正常工作,我正在尝试将变量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
关注者
0
被浏览
47
1 个回答
-
您应在此处或串联使用字符串格式化程序。对于串联,您必须将转换
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"
编辑 :正如JF Sebastian在评论中指出的,我们还可以执行以下操作
在Python 3.6中:
f"You are {age} years old"
Python的早期版本:
"You are {age} years old".format(**vars())