删除字符串中重复字符(字)的最佳方式? [英] Best way to remove duplicate characters (words) in a string?

查看:119
本文介绍了删除字符串中重复字符(字)的最佳方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我认为这个例子解释得更好:

  foo ='hkk h2 h'

应该成为:

  foo ='hk h2'#order not important 

其他示例:

  foo ='ss k'

成为:

  foo ='s k'


解决方案

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

请注意,split()默认将分割为所有空格字符。 (例如标签,换行符,空格)



所以如果你只想在一个空格上拆分,那么你必须使用:

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


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'

解决方案

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

这篇关于删除字符串中重复字符(字)的最佳方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆