从字符串中删除重复字符 [英] Removing duplicate characters from a string
问题描述
如何使用 Python 从字符串中删除重复字符?例如,假设我有一个字符串:
How can I remove duplicate characters from a string using Python? For example, let's say I have a string:
foo = 'mppmt'
如何制作字符串:
foo = 'mpt'
注意:顺序并不重要
推荐答案
如果顺序不重要,可以使用
If order does not matter, you can use
"".join(set(foo))
set()
将在字符串中创建一组唯一的字母,"".join()
将按任意顺序将字母连接回字符串.
set()
will create a set of unique letters in the string, and "".join()
will join the letters back to a string in arbitrary order.
如果顺序确实很重要,您可以使用 dict
而不是 set,因为 Python 3.7 保留了键的插入顺序.(在 CPython 实现中,这在 Python 3.6 中已作为实现细节支持.)
If order does matter, you can use a dict
instead of a set, which since Python 3.7 preserves the insertion order of the keys. (In the CPython implementation, this is already supported in Python 3.6 as an implementation detail.)
foo = "mppmt"
result = "".join(dict.fromkeys(foo))
产生字符串 "mpt"
.在早期版本的 Python 中,您可以使用 collections.OrderedDict
,它从 Python 2.7 开始可用.
resulting in the string "mpt"
. In earlier versions of Python, you can use collections.OrderedDict
, which has been available starting from Python 2.7.
这篇关于从字符串中删除重复字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!