Best way to remove duplicate characters (words) in a string?

duplicates, python, string

Solution

' '.join(set(foo.split()))

Note that split() by default will split on all whitespace characters. (e.g. tabs, newlines, spaces)

So if you want to split ONLY on a space then you have to use:

' '.join(set(foo.split(' ')))

Problem

What would be the best way of removing any duplicate characters and sets of characters separated by spaces in string? I think this example explains it better: ``` foo = 'h k k h2 h' ``` should become: ``` foo = 'h k h2' # order not important ``` Other example: ``` foo = 's s k' ``` becomes: ``` foo = 's k' ```

Original source