[英]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"]
输入字符串为
'{"abc": "##value##", "Xyz": 2}'
,我想用["v1", "v2"]
类的列表替换"##value##"
" ["v1", "v2"]
So, the output would look like '{"abc": ["v1", "v2"], "Xyz": 2}'
因此,output 看起来像
'{"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'
re.sub('##value##', replacement_value, input_data)
,但是这样做会产生不可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 re.sub()
只接受字符串作为替代,所以它相当于
import re
s = '{"abc": "##value##", "Xyz": 2}'
print(re.sub('"##value##"', '["v1", "v2"]', s))
Output: Output:
{"abc": ["v1", "v2"], "Xyz": 2}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.