Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/css/36.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 替换重复的字符串字符_Python_String_Replace_Duplicates_Iteration - Fatal编程技术网

Python 替换重复的字符串字符

Python 替换重复的字符串字符,python,string,replace,duplicates,iteration,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 我没有通过的测试如下: "("应该等于")"

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

下面是我的代码

def duplicate_encode(word):
new_word = ''
for char in word:
    if len(char) > 1:
        new_word += ')'
    else:
        new_word += '('
return new_word
我没有通过的测试如下:

"("应该等于")"


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

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

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')
# '()()()'

你的代码是好的,只是需要一些修改,这将是伟大的

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")
我想你得到了答案:)

只是因为(时间晚了,而且)有可能:

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

这是非常有用的!我忘了提到我想确保我的函数也忽略大小写。因此,以“Success”-它应该返回)()()())为例。您可以使用
.lower()
方法将单词转换为小写。请参阅更新。如果测试是这样的,则“((((()应该变成“()()”),您应该尝试将每个字符转换为“(”除非该字符与其前面的字符相同,否则应将其转换为“)”。“后退”以及大多数英语单词将保持不变。