Search code examples
pythonstringaccumulator

Python Removing Duplicates in a String Using in and not in


I'm trying to use the in and not in operators as well as the Accumulator Pattern to remove all duplicate letters from a string and return a new string while maintaining order.

withDups = "The Quick Brown Fox Jumped Over The Lazy Dog"

def removeDups(s):
    alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
    sWithoutDups = ""
    for eachChar in withDups:
        if eachChar in alphabet:
            sWithoutDups = eachChar + sWithoutDups
        return sWithoutDups

print(removeDups(withDups))

My current code returns only the first letter of the string. I'm very new to python and coding in general, so please excuse if I'm overlooking something simple, my current code is not even the right direction, or if I'm posting something that shouldn't be.


Solution

  • withDups = "The Quick Brown Fox Jumped Over The Lazy Dog"
    withoutDups = ""
    
    for letter in withDups:
        if letter not in withoutDups:
            withoutDups += letter
    
    print withoutDups
    

    Have in mind that whitespaces are considered a character too.