Python 查找并替换方括号之间的值
有人知道怎么得到这样的东西:Python 查找并替换方括号之间的值,python,python-2.7,Python,Python 2.7,有人知道怎么得到这样的东西: array = ["one", "two", "three"] str = "text123123text:[852],[456465],[1]" 我想替换括号之间的所有内容 output: text123123text:'one', 'two', 'three' 我通过re.sub('\[.*?\]','',str) 我得到了输出:text 123text:'','' 这当然是合乎逻辑的,但如何为每个子函数创建一个方法,该方法使用index replace参数
array = ["one", "two", "three"]
str = "text123123text:[852],[456465],[1]"
我想替换括号之间的所有内容
output: text123123text:'one', 'two', 'three'
我通过re.sub('\[.*?\]','',str)
我得到了输出:text 123text:'',''
这当然是合乎逻辑的,但如何为每个子函数创建一个方法,该方法使用index replace参数替换调用函数,然后从数组返回文本
在伪代码中,我认为:
array = ["one", "two", "three"]
def abstract_function(replace_index):
return array[replace_index]
str = "text123123text:[852],[456465],[1]"
print re.sub('\[.*?\]'," '$CALL:abstract_function$'", str)
output: text123123text:'one', 'two', 'three'
有什么方法可以解决我的问题吗?我想这样做
>>> stri = "text123123text:[852],[456465],[1]"
>>> array = ["one", "two", "three"]
>>> d = {i:j for i,j in zip(re.findall(r'\[[^\]]*\]', stri), array)} # create a dict with values inside square brackets as keys and array list values as values.
>>> d
{'[852]': 'one', '[456465]': 'two', '[1]': 'three'}
>>> re.sub(r'\[[^\]]*\]', lambda m: "'" + d[m.group()] + "'", stri) # replaces the key with the corresponding dict value.
"text123123text:'one','two','three'"
谢谢你,阿维纳什·拉吉:)