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

Putting a variable into a string (quote)

求助,我无法让它工作,我正在尝试将变量 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

您应该在此处使用字符串格式化程序或连接。对于串联,您必须将 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所述。评论中的塞巴斯蒂安我们还可以执行以下操作

在 Python 3.6:

f"You are {age} years old"

Python 的早期版本:

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

这是一种方法:

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

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

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

您可以在 Python's string documentation.

上阅读更多关于其他方法的信息

好吧,请检查一下别人再次询问的以下代码。

event_type_id = 26420387

### this is original post, need to add variable to 'eventTypeIds'
##events_req_format = '{' \
##             '"jsonrpc": "2.0", ' \
##             '"method": "SportsAPING/v1.0/listEvents", ' \
##             '"params": {"filter": {"eventTypeIds": ["26420387"]},' \
##             '"marketStartTime": {"from": "2022-03-12T00:00:00Z","to": "2022-03-13T23:59:00Z"}}},' \
##             '"id": 1' \
##             '}'

# added formatted string with variable event_type_id, used prefix f
events_req_format = '{' \
             '"jsonrpc": "2.0", ' \
             '"method": "SportsAPING/v1.0/listEvents", ' \
             '"params": {"filter": {"eventTypeIds": ["'\
             f'{event_type_id}'\
             '"]},' \
             '"marketStartTime": {"from": "2022-03-12T00:00:00Z","to": "2022-03-13T23:59:00Z"}}},' \
             '"id": 1' \
             '}'

用单引号或双引号引用的str是单行字符串。所以 '\' 只是为了方便而换行。并且所有被单引号引用的字符串都是一个 str, events_req_format.
我刚刚更改了字符串 {"eventTypeIds": ["26420387"]},'
如您所见,我为变量添加了带前缀 f 的格式化字符串。