Skip to content
Advertisement

How to remove characters that appear more than once from a string?

So, I had a similar exercise on my IT classes: ‘Print a string without characters appearing more than once (if they appear more than once, remove them)’. I thought that it was easy (and maybe it is), but I have completely no idea how to do that. I can do similar exercises (print all unique characters from a string / remove duplicates etc).

Example:

Input: ‘12345555555678’

Output: ‘1234678’

Advertisement

Answer

You could use collections.Counter().

from collections import Counter

inp = '12345555555678'
c = Counter(inp)
output = ''.join(k for k, v in c.items() if v == 1)  # -> 1234678

Simple implementation of Counter

c = {}
for char in inp:
    c[char] = c.get(char, 0) + 1
Advertisement