gpt4 book ai didi

python - 替换重复的字符串字符

转载 作者:行者123 更新时间:2023-12-01 03:40:03 26 4
gpt4 key购买 nike

我需要转换一个字符串 word,其中仅出现一次的每个字符应在新字符串中显示为 '('。原始字符串中的任何重复字符应替换为 ')'

下面是我的代码...

def duplicate_encode(word):
new_word = ''
for char in word:
if len(char) > 1:
new_word += ')'
else:
new_word += '('
return new_word

我没有通过的测试如下:

'((((('应等于'()()()'

这表明,例如,如果输入是“recede”,则输出应为 ()()()

最佳答案

你的代码很好,只需要一些修改就可以了。

def duplicate_encode(word):
"""
To replace the duplicate letter with ")" in a string.
if given letter is unique it replaced with "("
"""
word_dict = {} # initialize a dictionary
new_word = ""
for i in set(word): # this loop is used to count duplicate words
word_count = word.count(i)
word_dict[i] = word_count # add letter and count of the letter to dictionary
for i in word:
if word_dict[i] > 1:
new_word += ")"
else:
new_word += "("
print new_word

duplicate_encode("recede")

我想你已经找到答案了:)

关于python - 替换重复的字符串字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39737196/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com