[英]Concatenate index of a list into a string variables
lets say if list = ['1a-b2', '2j-u3', '5k-hy']
then how can I add each index in a loop in something like假设如果
list = ['1a-b2', '2j-u3', '5k-hy']
那么我如何在循环中添加每个索引,例如
main = '{"datatype: null" "country_code":"eu","offset":0,"id":"1h-j3"}'
I want to replace the "1h-j3" in the main with my indexes in a loop, I have tried to concatenate using +, % but they did not work, kindly help me with this.我想用循环中的索引替换 main 中的“1h-j3”,我尝试使用 +、% 进行连接,但它们不起作用,请帮我解决这个问题。 Both the list indexes and main variable are of data type string
列表索引和主变量都是数据类型字符串
Well, I can think of 2 approaches, based on the type of data you have for the main
variable.好吧,我可以根据您对
main
变量的数据类型想到 2 种方法。 See below.见下文。
In case, the value is a proper JSON如果值是正确的 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)
Other case, its a dirty string manipulation.其他情况下,它是一个肮脏的字符串操作。 May be there are better ways,
可能有更好的方法,
# 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)
produced output生产 output
{"datatype: null" "country_code":"eu","offset":0,"id":"3"}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.