Python: Best Way to remove duplicate character from string

后端 未结 7 895
借酒劲吻你
借酒劲吻你 2020-12-01 21:46

How can I remove duplicate characters from a string using Python? For example, let\'s say I have a string:

foo = \"SSYYNNOOPPSSIISS\"

How c

7条回答
  •  庸人自扰
    2020-12-01 22:09

    def remove_duplicates(astring):
      if isinstance(astring,str) :
        #the first approach will be to use set so we will convert string to set and then convert back set to string and compare the lenght of the 2
        newstring = astring[0]
        for char in astring[1:]:
            if char not in newstring:
                newstring += char    
        return newstring,len(astring)-len(newstring)
      else:
    raise TypeError("only deal with alpha  strings")
    

    I've discover that solution with itertools and with list comprehesion even the solution when we compare the char to the last element of the list doesn't works

提交回复
热议问题