简体   繁体   中英

Replace with regular expression a string with a list of strings in python

I want to replace part of a string with a list of strings

Eg. with an input string of '{"abc": "##value##", "Xyz": 2}' , I want to replace "##value##" with some list like ["v1", "v2"]

So, the output would look like '{"abc": ["v1", "v2"], "Xyz": 2}'

If the replacement were not a list I would have just used

re.sub('##value##', replacement_value, input_data) , however doing so gives an error of unhashable type: 'list'

Is there another way to achieve this?

Simply change

re.sub('##value##', replacement_value, input_data)

to

re.sub("'##value##'", str(replacement_value), input_data)

re.sub() only takes in strings as the substitutes, so it's the equivalent of

import re
s = '{"abc": "##value##", "Xyz": 2}'
print(re.sub('"##value##"',  '["v1", "v2"]', s))

Output:

{"abc": ["v1", "v2"], "Xyz": 2}

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