查找并替换方括号之间的值

时间:2016-02-15 14:38:09

标签: python python-2.7

有人知道怎么样:

array = ["one", "two", "three"]
str = "text123123text:[852],[456465],[1]"

我希望在括号之间替换所有结果

output: text123123text:'one', 'two', 'three'

我尝试re.sub('\[.*?\]'," ''", str) 我得到output: text123123text:'', '', '' 它当然是合乎逻辑的,但是如何为每个sub替换调用函数的create方法用index替换参数,然后从数组返回文本。

在伪代码中我想象:

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'

是否存在解决问题的方法?

1 个答案:

答案 0 :(得分:2)

我会这样做,

>>> 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'"