from itertools import groupby
def rep_adj(data, char='z'):
for _, v in groupby(data):
b = list(v)
if len(b) > 0:
for i, j in enumerate(b):
yield char if not i%2==0 else j
data = 'xyxxxyx'
out = ''.join(rep_adj(data))
print(out)
a='xyxxxyx'
import string
from random import randint
total=[x for x in list(string.ascii_lowercase) if x not in spil] # gets alphabets a to z in a list except the ones in a
spil=list(a) #spilt the string a in letters
for i in range(len(spil)-1):
if spil[i]==spil[i+1]: #if two consecitive are same then changes the next one with a random alphabet
spil[i]=total[randint(0,len(total))]
print("".join(spil))
以下是一种使用
groupby
模块中的itertools
解决问题的方法:输出:
可以使用正则表达式执行此操作:
表达式(.)(\1+)查找字符串的第一个字符和随后的重复字符。循环遍历匹配项将允许您用交替的字符模式替换后续部分,这些字符既不是重复的字符,也不是紧跟其后的字符。你需要使用一个交替的模式来替换,这样你就不会产生新的重复。你知道吗
请注意,我们只需要处理4个替换字符,因为重复字符和下一个字符要么是4个字符中的一个或两个(留下两个用于替换),要么一个都不需要(这允许我们使用4个字符中的任意两个)。你知道吗
这将达到以下目的:
输出为:
相关问题 更多 >
编程相关推荐