替换重复的字符串字符

时间:2016-09-28 02:42:22

标签: python string replace duplicates iteration

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

我的代码如下......

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

我没有通过的测试如下:

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

这表明,例如,如果输入是"后退,"输出应为()()()

3 个答案:

答案 0 :(得分:1)

你的守则是好的只需要做一些改动就会很棒。

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

我认为你得到了答案:)

答案 1 :(得分:1)

只是因为(它已经很晚了)它可能:

def duplicate_encode(word):

    return (lambda w: ''.join(('(', ')')[c in w[:i] + w[i+1:]] for i, c in enumerate(w)))(word.lower())

print(duplicate_encode("rEcede"))

输出

> python3 test.py
()()()
>

答案 2 :(得分:0)

似乎您的结果基于单词中出现的字符数,您可以使用Counter来跟踪:

def duplicate_encode(word):
    from collections import Counter

    word = word.lower()              # to disregard case
    counter = Counter(word)
    new_word = ''
    for char in word:
        if counter[char] > 1:        # if the character appears more than once in the word 
                                     # translate it to )
            new_word += ')'
        else:
            new_word += '('
    return new_word

duplicate_encode('recede')
# '()()()'