List of all unique characters in a string?

后端 未结 7 1535
再見小時候
再見小時候 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:19

    I have an idea. Why not use the ascii_lowercase constant?

    For example, running the following code:

    # string module, contains constant ascii_lowercase which is all the lowercase
    # letters of the English alphabet
    import string
    # Example value of s, a string
    s = 'aaabcabccd'
    # Result variable to store the resulting string
    result = ''
    # Goes through each letter in the alphabet and checks how many times it appears.
    # If a letter appears at least oce, then it is added to the result variable
    for letter in string.ascii_letters:
        if s.count(letter) >= 1:
            result+=letter
    
    # Optional three lines to convert result variable to a list for sorting
    # and then back to a string
    result = list(result)
    result.sort()
    result = ''.join(result)
    
    print(result)
    

    Will print 'abcd'

    There you go, all duplicates removed and optionally sorted

提交回复
热议问题