在python中,如何将字符串中的一个字母替换为除其自身或相邻字母以外的任何其他字母

2024-05-14 18:35:40 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个字符串'xyxxxyx'。我想将中间的x替换为除(xy(相邻字母)之外的任何其他字母,以生成一个字符串,这样每个相邻字母都是不同的。你知道吗

举个例子

Input: 'xyxxxyx'  
Output: 'xyxzxyx' 

我想这是通用的任何输入字符串。你知道吗


Tags: 字符串inputoutput字母例子xyxxxyxxyxzxyx
3条回答

以下是一种使用groupby模块中的itertools解决问题的方法:

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)

输出:

'xyxzxyx'

可以使用正则表达式执行此操作:

import re

def noDoubles(string):
    subChars = set("wxyz")
    result   = list(string)
    for match in re.finditer(r"(.)(\1+)",string):
        usedChars = set(string[match.start():match.end()+1])
        altChars  = list(subChars - usedChars)
        size      = match.end(2) - match.start(2)
        size      = size - (size>1) 
        result[match.start(2):match.start(2)+size] = (altChars[:2]*size)[:size]
    return "".join(result)

print(noDoubles("xyxxxyaaabbyyaaaaa")) # "xyxzxyazabzyzazwza"

表达式(.)(\1+)查找字符串的第一个字符和随后的重复字符。循环遍历匹配项将允许您用交替的字符模式替换后续部分,这些字符既不是重复的字符,也不是紧跟其后的字符。你需要使用一个交替的模式来替换,这样你就不会产生新的重复。你知道吗

请注意,我们只需要处理4个替换字符,因为重复字符和下一个字符要么是4个字符中的一个或两个(留下两个用于替换),要么一个都不需要(这允许我们使用4个字符中的任意两个)。你知道吗

这将达到以下目的:

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))

输出为:

'xyczxyx'

相关问题 更多 >

    热门问题