Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 查找并替换方括号之间的值_Python_Python 2.7 - Fatal编程技术网

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

谢谢你,阿维纳什·拉吉:)