如何在 python 中的字符串中添加变量?
How do I add variables within string in python?
我正在编写 python 代码以通过 cURL 抓取网站数据。我使用 https://curlconverter.com/ 将 cURL 转换为 python 代码。代码工作得很好,但我想根据我的需要自定义,就像在这行代码中一样
data = '{"appDate":{"startDate":"2022-01-05T18:30:00.000Z","endDate":"2022-01-06T18:30:00.000Z"},"page_number":1,"page_size":20,"sort":{"key":"AppointmentStartTime","order":-1}}'
在“startDate”之后我想添加我这样创建的变量 (startdate)
variable code
我试过这样添加变量
data = '{"appDate":{"startDate":'+ startdate +,"endDate":'+ enddate +'},"page_number":1,"page_size":20,"sort":{"key":"AppointmentStartTime","order":-1}}'
但这没有用。
添加“+ str(startdate) +”也没有帮助。
谁能告诉我应该怎么做。
您可能希望使用 json module 将 json 数据字符串转换为字典。然后您就可以自由地操作和导出您的数据了。
import json
raw_data = '{"appDate":{"startDate":"2022-01-05T18:30:00.000Z","endDate":"2022-01-06T18:30:00.000Z"},"page_number":1,"page_size":20,"sort":{"key":"AppointmentStartTime","order":-1}}'
data = json.loads(raw_data) # load json from string to dict
data['appDate']['startDate'] = 23
data['appDate']['endDate'] = 42
print(json.dumps(data)) # export dict to json string
在您显示的示例中,在 + startdate +
之后可能只有一个小错误,即撇号。仔细比较:
你的代码(有错误):
data = '{"appDate":{"startDate":'+ startdate +,"endDate":'+ enddate +'},"page_number":1,"page_size":20,"sort":{"key":"AppointmentStartTime","order":-1}}'
^
SyntaxError: invalid syntax
固定码:
data = '{"appDate":{"startDate":'+ startdate +',"endDate":'+ enddate +'},"page_number":1,"page_size":20,"sort":{"key":"AppointmentStartTime","order":-1}}'
我正在编写 python 代码以通过 cURL 抓取网站数据。我使用 https://curlconverter.com/ 将 cURL 转换为 python 代码。代码工作得很好,但我想根据我的需要自定义,就像在这行代码中一样
data = '{"appDate":{"startDate":"2022-01-05T18:30:00.000Z","endDate":"2022-01-06T18:30:00.000Z"},"page_number":1,"page_size":20,"sort":{"key":"AppointmentStartTime","order":-1}}'
在“startDate”之后我想添加我这样创建的变量 (startdate)
variable code
我试过这样添加变量
data = '{"appDate":{"startDate":'+ startdate +,"endDate":'+ enddate +'},"page_number":1,"page_size":20,"sort":{"key":"AppointmentStartTime","order":-1}}'
但这没有用。
添加“+ str(startdate) +”也没有帮助。
谁能告诉我应该怎么做。
您可能希望使用 json module 将 json 数据字符串转换为字典。然后您就可以自由地操作和导出您的数据了。
import json
raw_data = '{"appDate":{"startDate":"2022-01-05T18:30:00.000Z","endDate":"2022-01-06T18:30:00.000Z"},"page_number":1,"page_size":20,"sort":{"key":"AppointmentStartTime","order":-1}}'
data = json.loads(raw_data) # load json from string to dict
data['appDate']['startDate'] = 23
data['appDate']['endDate'] = 42
print(json.dumps(data)) # export dict to json string
在您显示的示例中,在 + startdate +
之后可能只有一个小错误,即撇号。仔细比较:
你的代码(有错误):
data = '{"appDate":{"startDate":'+ startdate +,"endDate":'+ enddate +'},"page_number":1,"page_size":20,"sort":{"key":"AppointmentStartTime","order":-1}}'
^
SyntaxError: invalid syntax
固定码:
data = '{"appDate":{"startDate":'+ startdate +',"endDate":'+ enddate +'},"page_number":1,"page_size":20,"sort":{"key":"AppointmentStartTime","order":-1}}'