Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/294.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.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-如何使用正则表达式用n个发生率替换子字符串_Python_Regex_String - Fatal编程技术网

Python-如何使用正则表达式用n个发生率替换子字符串

Python-如何使用正则表达式用n个发生率替换子字符串,python,regex,string,Python,Regex,String,我有一个字符串,有很多重复出现的单一模式,比如 a = 'eresQQQutnohnQQQjkhjhnmQQQlkj' 我有另一根线,像 b = 'rerTTTytu' 我想替换整个第二个字符串,将“QQQ”和“TTT”作为引用,在本例中,我想找到3个不同的结果: 'ererTTTytuohnQQQjkhjhnmQQQlkj' 'eresQQQutnrerTTTytujhnmQQQlkj' 'eresQQQutnohnQQQjkhjrerTTTytu' 我试过使用re.sub re.sub

我有一个字符串,有很多重复出现的单一模式,比如

a = 'eresQQQutnohnQQQjkhjhnmQQQlkj'
我有另一根线,像

b = 'rerTTTytu'
我想替换整个第二个字符串,将“QQQ”和“TTT”作为引用,在本例中,我想找到3个不同的结果:

'ererTTTytuohnQQQjkhjhnmQQQlkj'
'eresQQQutnrerTTTytujhnmQQQlkj'
'eresQQQutnohnQQQjkhjrerTTTytu'
我试过使用re.sub

re.sub('\w{3}QQQ\w{3}' ,b,a)

但是我只得到了第一个,我不知道如何得到另外两个解决方案。

编辑:按照您的要求,围绕“QQQ”的两个字符现在也将被替换。

我不知道这是解决这个问题的最优雅或最简单的解决方案,但它是有效的:

import re

# Find all occurences of ??QQQ?? in a - where ? is any character
matches = [x.start() for x in re.finditer('\S{2}QQQ\S{2}', a)]
# Replace each ??QQQ?? with b
results = [a[:idx] + re.sub('\S{2}QQQ\S{2}', b, a[idx:], 1) for idx in matches]

print(results)
输出

['errerTTTytunohnQQQjkhjhnmQQQlkj',
'eresQQQutnorerTTTytuhjhnmQQQlkj',
'eresQQQutnohnQQQjkhjhrerTTTytuj']

由于您没有指定输出格式,我只是将其放在一个列表中。

编辑:根据您的要求,“QQQ”周围的两个字符现在也将被替换。

我不知道这是解决这个问题的最优雅或最简单的解决方案,但它是有效的:

import re

# Find all occurences of ??QQQ?? in a - where ? is any character
matches = [x.start() for x in re.finditer('\S{2}QQQ\S{2}', a)]
# Replace each ??QQQ?? with b
results = [a[:idx] + re.sub('\S{2}QQQ\S{2}', b, a[idx:], 1) for idx in matches]

print(results)
输出

['errerTTTytunohnQQQjkhjhnmQQQlkj',
'eresQQQutnorerTTTytuhjhnmQQQlkj',
'eresQQQutnohnQQQjkhjhrerTTTytuj']

由于您没有指定输出格式,我只是将其放在一个列表中。

问题是,我还必须更改原始字符串中的前两个字符和后两个字符,您将它们保留在最后一个字符串中。我只是更新了我的答案,“QQQ”之前和之后的两个字符也将被替换。今后,请尝试在您的问题中添加更易于阅读的示例。从一个随机的字符串中找出你想要做什么真的很困难。我将在下一个问题中牢记这一点!非常感谢你!问题是,我还必须更改原始字符串中的前两个字符和后两个字符,您将它们保留在最后一个字符串中。我刚刚更新了我的答案,“QQQ”之前和之后的两个字符也将被替换。今后,请尝试在您的问题中添加更易于阅读的示例。从一个随机的字符串中找出你想要做什么真的很困难。我将在下一个问题中牢记这一点!非常感谢你!