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()
方法将单词转换为小写。请参阅更新。如果测试是这样的,则“((((()应该变成“()()”),您应该尝试将每个字符转换为“(”除非该字符与其前面的字符相同,否则应将其转换为“)”。“后退”以及大多数英语单词将保持不变。