简体   繁体   中英

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

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. 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. See below.

In case, the value is a proper 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

{"datatype: null" "country_code":"eu","offset":0,"id":"3"}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM