1

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?

1 Answer 1

1

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}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.