Alex Rivera | Logout

How can I remove duplicate words in a string with Python?

Asked 2011-10-17T13:08:35.987
44

Following example:

string1 = "calvin klein design dress calvin klein"

How can I remove the second two duplicates "calvin" and "klein"?

The result should look like

string2 = "calvin klein design dress"

only the second duplicates should be removed and the sequence of the words should not be changed!

Edit
Report

1 Answer

5
string = 'calvin klein design dress calvin klein'

def uniquify(string):
    output = []
    seen = set()
    for word in string.split():
        if word not in seen:
            output.append(word)
            seen.add(word)
    return ' '.join(output)

print uniquify(string)
answered 2011-10-17T13:27:56.220

Your Answer