我有一個清單
list = ['1a-b2', '2j-u3', '5k-hy', '1h-j3']
我有一個像下面這樣的字串
main = '{"datatype: null" "country_code":"eu","offset":0,"id":"2y-9k"}'
如何id用主串列中的相應索引替換字串中的值?
例如,我想main用它的索引替換字串中的“1h-j3” list。這也將在回圈中完成。
我曾嘗試使用 , % 進行連接,但它們不起作用,請幫助我解決這個問題。串列索引和主變數都是字串資料型別
第一個回圈中的預期輸出如下
main = '{"datatype: null" "country_code":"eu","offset":0,"id":"1a-b2"}'
在第二個回圈中
main = '{"datatype: null" "country_code":"eu","offset":0,"id":"2j-u3"}'
在第三個回圈中
main = '{"datatype: null" "country_code":"eu","offset":0,"id":"5k-hy"}'
等等
uj5u.com熱心網友回復:
好吧,根據您擁有的main變數資料型別,我可以想到 2 種方法。見下文。
如果值是正確的 JSON
import json
items_list = ['1a-b2', '2j-u3', '5k-hy', "1h-j3"]
# if main_dict was a valid json
main_dict = json.loads('{"datatype": "null", "country_code":"eu","offset":0,"id":"1h-j3"}')
main_dict["id"] = items_list.index(main_dict["id"])
main_dict = json.dumps(main_dict)
其他情況,它是一個骯臟的字串操作。可能有更好的方法,
# If its not a valid JSON
str_main = '{"datatype: null" "country_code":"eu","offset":0,"id":"1h-j3"}'
import re
# Use a regex to find the key for replacement.
found = re.findall(r'"id":".*"', str_main, re.IGNORECASE)
if found and len(found) > 0:
key = found[0].split(":")[1].replace('"', '')
_id = items_list.index(key)
str_main = str_main.replace(key, str(_id))
print(str_main)
產出
{"datatype: null" "country_code":"eu","offset":0,"id":"3"}
- 更新 -
根據您更新的要求,這將是一個簡單的回圈,我假設如下所示。
items_list = ['1a-b2', '2j-u3', '5k-hy', "1h-j3"]
base_str = '{"datatype: null" "country_code":"eu","offset":0,"id":"_ID_"}'
for item in items_list:
main = base_str.replace('_ID_', item)
print(main)
產生輸出如
{"datatype: null" "country_code":"eu","offset":0,"id":"1a-b2"}
{"datatype: null" "country_code":"eu","offset":0,"id":"2j-u3"}
{"datatype: null" "country_code":"eu","offset":0,"id":"5k-hy"}
{"datatype: null" "country_code":"eu","offset":0,"id":"1h-j3"}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/382208.html
上一篇:即使我正在檢查串列值也被覆寫
