我有下面的负载,我想用它来发出post请求。如果我希望"年龄"、"平均家庭规模"one_answers"城市"的每个值都是变量,我该如何重新格式化?
payload = "{"Age": "50",n "Average Family Size": "2.5",n "City": "Washington"}"
这是F字符串的一个很好的用法。
假设您的变量命名为age
、size
和city
:
payload = f'{"Age": "{age}",n "Average Family Size": "{size}",n "City": "city"}'
Python 2.7老式%s
字符串插值:
payload = f'{"Age": "%s",n "Average Family Size": "%s",n "City": "%s"}' % (age, size, city)
此外,通过将整个字符串用单引号括起来,您不必转义双引号。
您可以使用字典和json模块,不过,如果您可以使用更现代的python版本,f-string会更好:
import json
def get_payload(age, family_size, city):
return json.dumps({
"Age": age,
"Average Family Size": family_size,
"City": city
})
print(get_payload(21, 2, 'Washington DC'))
输出:
{"Age": 21, "Average Family Size": 2, "City": "Washington DC"}