如何使用Python删除重复字符串?

如何使用Python删除重复字符串?,python,string,duplicates,Python,String,Duplicates,我要学习python,我有一个问题要处理 以下示例: string1 = "Galaxy S S10 Lite" string2 = "Galaxy Note Note 10 Plus" 如何删除后两个重复的“S”和“S”或“Note”和“Note” 结果应该是这样的 string1a = "Galaxy S10 Lite" string2a = "Galaxy Note 10 Plus" 如何仅删除第二个副本,

我要学习python,我有一个问题要处理 以下示例:

string1 = "Galaxy S S10 Lite"
string2 = "Galaxy Note Note 10 Plus"
如何删除后两个重复的“S”和“S”或“Note”和“Note”

结果应该是这样的

string1a = "Galaxy S10 Lite"
string2a = "Galaxy Note 10 Plus"
如何仅删除第二个副本,并且不应更改单词的顺序

string1a = string1.split()
del string1a[1]
string1a = " ".join(string1a)
这符合您对提供的2个字符串的要求。
如果您确定字符串的第二个和第三个单词是重复的,并且优先选择第三个,那么它将只在您想要的所有字符串中工作。

接受的答案仅手动删除句子中的第二个单词。 如果你有一根很长的绳子,清理起来会很乏味

我想只有两种情况:

  • 如果与下列单词的第一个字母相同,请跳过该字母
  • 如果该词与后面的词相同,则跳过该词
  • 此功能可自动清洗

    def clean_string(string):
        """Clean if there were sequentially duplicated word or letter"""
        following_word = ''
        complete_words = []
        # loop through the string in reverse to be able to skip the earlier word/letter
        # string.split() splits your string by each space and make it as a list
        for word in reversed(string.split()):
            # to skip duplicated letter, in your case is to skip "S" and retain "S10"
            if (len(word) == 1) and (following_word[0] == word):
                following_word = word
                continue
            # to skip duplicated word, in your case is to skip "Note" and retain latter "Note"
            elif word == following_word:
                following_word = word
                continue
            following_word = word
            complete_words.append(word)
        # join all appended word and re-reverse it to be the expected sequence
        return ' '.join(reversed(complete_words))
    

    我会使用split并删除数组的第二个位置。@Capie我假设“s”和“S10”不是同一个单词,但不能保证单词始终位于第二位。没有什么神奇的功能可以仅仅假设并做你想做的事情。@AKX不要假设得那么快,让作者回答。在我看来,他得到了两个字符串,其中第一个字符串是前两个项目,而scond字符串是最后两个项目。结构总是像string1或string2,我只想删除第二和第三位置的12个连续相同的单词,输出将像string1a或string2a