python - 如何在 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
。但是,当我测试另一个输入时,例如heythere
,IndexError: string index out of range
显示在elif
第 12 行。如何使此代码适用于所有输入?
解决方案
您可以使用正则表达式来实现这一点。对于这两种方法,它都适用于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
作为输出。
我认为第二种方法会更合适。
推荐阅读
- angular - 'ModalController' 类型上不存在属性 'present'
- git - 如何让 yarn.lock 指向最近的提交
- spring - 如何在 antMatchers 中使用“包含”?
- r - R:使用 dplyr 将行除以行总计
- maven - 如何从 Maven Central 填充私有 Artifactory
- botframework - luisRecognizer 根据用户在版本#4 节点 js 中的首选语言环境选择 LUIS 模型
- amazon-web-services - 如何使用 AWS CDK 将元数据添加到 IAM 策略?
- java - 我如何在 spock 测试中使用 redisService 我需要清理 redis 数据库以进行设置和清理
- ruby-on-rails - Rails:使用 RestClient 进行外部 API 集成(400 错误请求)
- javascript - 如何打印报表