首页 > 解决方案 > 如何在 Python 中用“x”分割重复的字母?

问题描述

我正在尝试创建一个函数,该函数能够检测两个背靠背字母何时重复,例如“hello”中的 ls,并用字母“x”分割重复的字母。这是我的代码:

plaintext = input("Enter plaintext here: ")

plaintext = plaintext.lower() # makes plaintext lowercase
plaintext = plaintext.replace(" ", "") # removes all spaces

# this separates all duplicate letters

i = 0 # sets i to 0
for letter in plaintext:
    if plaintext[-1] == plaintext[-2]: # if the last letter is the same as the second to last
        plaintext = plaintext[:-1] + "x" + plaintext[-1:] # separate them with an x
    elif plaintext[i] == plaintext [i+1]: # if one letter is the same as the next letter
        # the line above makes an error
        plaintext = plaintext[:i+1] + "x" + plaintext[i+1:] #separate them with an x
        i += 1
    else:
        i += 1

当我作为输入输入时,此代码有效hello there;我收到helxlothere。但是,当我测试另一个输入时,例如heythereIndexError: string index out of range显示在elif第 12 行。如何使此代码适用于所有输入?

标签: python

解决方案


您可以使用正则表达式来实现这一点。对于这两种方法,它都适用于hello there hey there 发生两个以上字符重复时的不同之处。

方法1

import re
string='hello there'
# find Any repeated character and add x in between them
answer = re.sub(r'(.)\1{1}', r'\1x\1', string)
print(answer)

这里是hellllo there文本,你会得到输出helxllxlo there

方法2

或者,您可以使用此方法。

s="hello there"

for match in re.finditer(r"(.)\1+", s):
    old=s[match.start():match.end()]
    s=s.replace(old,'x'.join(old))
print(s)

这里是hellllo there文本,你会得到输出helxlxlxlo there作为输出。

我认为第二种方法会更合适。


推荐阅读