首页 > 解决方案 > python - 如何将变量放在python中的一个sting字典中?

问题描述

我正在尝试与 Trakt.tv api 交互,但我正在努力在字符串字典中创建一个变量。

api OAuth 调用服务器,提供 2 个访问代码,其中一个代码需要转发到以下服务器调用。像这样:

values = """{
    "code": "code provide by the api",
    "client_id": "code provide by user",
    "client_secret": "code provide by user"
  }
""" 
headers = {
  'Content-Type': 'application/json'
}
request = Request('https://api.trakt.tv/oauth/device/token', data=values, headers=headers)

我在变量 api_code 中有所需的代码,并希望将此变量放在字符串中,如下例所示。

values = """{
    "code": f"api_code",
    "client_id": f"user_code",
    "client_secret": f"user_code_2"
  }
""" 
headers = {
  'Content-Type': 'application/json'
}
request = Request('https://api.trakt.tv/oauth/device/token', data=values, headers=headers)

标签: pythondictionaryvariablesstring-formatting

解决方案


IIUC 你可以.format()这样使用:

values = """{{
    "code": f"{0}",
    "client_id": f"user_code",
    "client_secret": f"user_code_2"
  }}
""" 

api_code = 'abc123'
values = values.format(api_code)

请注意,为了获取{}格式字符串中的实际字符,您需要将它们加倍,就像我在第 1 行和第 4 行中所做的那样


推荐阅读