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

随声附和 提交于 2019-12-19 10:13:34

问题


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'

回答1:


' '.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(' ')))



回答2:


Do you mean?

' '.join( set( someString.split() ) )

That's the unique space-delimited words in no particular order.




回答3:


out = []
for word in input.split():
    if not word in out:
        out.append(word)
output_string = " ".join(out)

Longer than using a set, but it keeps the order.

Edit: Nevermind. I missed the part in the question about order not being important. Using a set is better.



来源:https://stackoverflow.com/questions/636977/best-way-to-remove-duplicate-characters-words-in-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!