Search code examples
pythonmethodsreplacelogic

Differect Result with Replace method in Python


Context : I'm writing a program to find 1st non-repeating letter in a string.

TEST CODE I need to implement following logic :

s = "iiiiiiitya"
if 'i' in s:
    s = s.replace('i','')
print(s)

OUTPUT : tya

Which is fine. It removes all the occurances of 'i' from the string. That is what I wanted.

PROBLEM : But as soon as I start to implement same logic in my actual program, the function doesn't work the same i.e. It only removes only 1st occurance of the perticulare letter and hence my logic fails.

def non_rep(s):
    for el in s:
        if el in s[1:]:
            s = s.replace(el,'')
        else:
            return el
    return "No such case is matched"
str = "adiiiityda"
ch = non_rep(str)
print(ch)

OUTPUT : i

EXPECTED OUTPUT : t

Why does it behave in such way, I tried a lot, but it works like it should in the first(test) code and when I implement it into program it behave differently.


Solution

  • You can use collections.Counter to get the counts, then keep only the unique values:

    from collections import Counter
    
    s = "iiiiiiitya"
    
    c = Counter(s)
    ''.join([i for i in c if c[i]==1])
    

    output: tya