[英]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.