[英]Concatenate index of a list into a string variables
假設如果list = ['1a-b2', '2j-u3', '5k-hy']
那么我如何在循環中添加每個索引,例如
main = '{"datatype: null" "country_code":"eu","offset":0,"id":"1h-j3"}'
我想用循環中的索引替換 main 中的“1h-j3”,我嘗試使用 +、% 進行連接,但它們不起作用,請幫我解決這個問題。 列表索引和主變量都是數據類型字符串
好吧,我可以根據您對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)
生產 output
{"datatype: null" "country_code":"eu","offset":0,"id":"3"}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.