Python 将变量放入字符串中(引用)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37015485/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Putting a variable into a string (quote)
提问by Tim
Help I can't get this to work, I am trying to put the variable age into the string but it won't load the variable properly.
帮助 我无法让它工作,我试图将变量 age 放入字符串中,但它无法正确加载变量。
Here is my code:
这是我的代码:
import random
import sys
import os
age = 17
print(age)
quote = "You are" age "years old!"
Gives this error:
给出这个错误:
File "C:/Users/----/PycharmProjects/hellophyton/hellophyton.py", line 9
quote = "You are" age "years old!"
^
SyntaxError: invalid syntax
Process finished with exit code 1
回答by Pythonista
You should use a string formatter here, or concatenation. For concatenation you'll have to convert an int
to a string
. You can't concatenate ints and strings together.
您应该在此处使用字符串格式化程序或连接。对于串联,您必须将 an 转换int
为 a string
。您不能将整数和字符串连接在一起。
This will raise the following error should you try:
如果您尝试,这将引发以下错误:
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Formatting:
格式化:
quote = "You are %d years old" % age
quote = "You are {} years old".format(age)
Concatenation (one way)
串联(一种方式)
quote = "You are " + str(age) + " years old"
Edit: As noted by J.F. Sebastian in the comment(s) we can also do the following
编辑:正如 JF Sebastian 在评论中所指出的,我们还可以执行以下操作
In Python 3.6:
在 Python 3.6 中:
f"You are {age} years old"
Earlier versions of Python:
早期版本的 Python:
"You are {age} years old".format(**vars())
回答by Joe T. Boka
This is one way to do it:
这是一种方法:
>>> age = 17
>>> quote = "You are %d years old!" % age
>>> quote
'You are 17 years old!'
>>>
回答by gr1zzly be4r
You need to use the +
sign to insert it into the string like this:
您需要使用该+
符号将其插入字符串中,如下所示:
quote = "You are " + age + " years old!"
You can read more about other ways of doing this on Python's string documentation.
您可以在Python 的字符串文档 中阅读更多有关执行此操作的其他方法的信息。