删除重复项时,请保留数字

3
这是我用来移除字符串中重复字母的代码。

word=input()

def dup_find(word):
    empty = ""  
    for character in word:
        if character not in empty or character == " ":
            empty = empty + character
    return empty


当输入为"6969 macaroni"时,输出结果为"69 macroni",但我希望数字保持不变,只删除重复的字母,所以输出应该是:6969 macroni。
感谢您的帮助。

1
只需要将你的if语句更改为 if letter.isdigit() or (letter not in x or letter == ...): - ssp
实际上应该是 if letter.isdigit() or letter not in x ... - Barmar
那些有重复字母的合法单词怎么办,例如“book”,或者有重复字母序列的单词,例如“barbaric”? - Tim Biegeleisen
3个回答

1
这是正确的方式。
text="Enter string:"+" "
string=input(text)

def rem_duplicates(string):
    x = ""  
    for letter in string:
        if letter.isdigit() or letter not in x or letter == ' ':
            x = x + letter
    return x

print(rem_duplicates(string))

嗨,当识别数字时,使用isdigit还是isnumeric有什么区别吗? - redshorts17
isdigit() 检查字符是否在 0-9 范围内,无论是数字还是字符串,但 isnumeric() 还将检查字符串的类型。 - Aliasgher Nooruddin

1
检查字符串中的字符是否来自于isnumeric()函数,然后设置您的条件。 letter == ' '不是必需的,但您也可以设置它。
text = "Enter string:"+" "
string = input(text)

def rem_duplicates(string):
    x = ""
    for letter in string:
        if letter.isnumeric() or letter not in x or letter == ' ':
            x = x + letter
    return x


print(rem_duplicates(string))

它会打印出“请输入字符串:”和一个空格,然后是您的输入。 - redshorts17
@Dav_DidHu 的文本是供用户选择的。在问题中并不需要,但提到了文本。 - mhhabib

1

试试这个:

text = "Enter string: " # just do the space in the string
string = input(text)


def rem_duplicates(string):
    x = ""
    for letter in string:
        if letter.isdigit() or letter not in x or letter == " ": # if the string is a number or letter is empty or letter not in x
            x = x + letter
    return x


print(rem_duplicates(string))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接