繁体   English   中英

删除字符串中的常见字符或重复项

[英]Remove common characters or duplicates in a string

我正在尝试在用户输入时删除字符串中的重复项。 这是我的代码:

userinput = input("Enter a word:")
def duplicates_removal(x):
      for i in range(len(x)-1):
             if x[i] == x[i +1]:
                     return duplicates_removal(x.replace(x[i], ' '))
      return x 

print(duplicates_removal(userInput))

当我运行代码并输入字符串Bananas时,它将生成输出Bananas,其中重复项未删除。 代码中是否有任何缺陷? 另外,我更喜欢不使用内置函数,因为我刚刚开始学习字符串操作。

Input: Bananas
Output desired: Bans
def duplicates_removal(x):
    l = []
    for each in x:
        if each not in l:
            l.append(each)
    return "".join(l)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM