List of all unique characters in a string?

后端 未结 7 1531
再見小時候
再見小時候 2020-11-27 18:03

I want to append characters to a string, but want to make sure all the letters in the final list are unique.

Example: \"aaabcabccd\"

相关标签:
7条回答
  • 2020-11-27 18:37

    The simplest solution is probably:

    In [10]: ''.join(set('aaabcabccd'))
    Out[10]: 'acbd'
    

    Note that this doesn't guarantee the order in which the letters appear in the output, even though the example might suggest otherwise.

    You refer to the output as a "list". If a list is what you really want, replace ''.join with list:

    In [1]: list(set('aaabcabccd'))
    Out[1]: ['a', 'c', 'b', 'd']
    

    As far as performance goes, worrying about it at this stage sounds like premature optimization.

    0 讨论(0)
提交回复
热议问题