Search code examples
pythonstringlist

Remove equal characters from two python strings


I am writing a Python code to remove equal same characters from two strings which lies on the same indices. For example remove_same('ABCDE', 'ACBDE') should make both arguments as BC and CB. I know that string is immutable here so I have converted them to list. I am getting an out of index error.

def remove_same(l_string, r_string):
    l_list = list(l_string)
    r_list = list(r_string)
    i = 0
    while i != len(l_list):
        print(f'in {i} length is {len(l_list)}')
        while l_list[i] == r_list[i]:
            l_list.pop(i)
            r_list.pop(i)
        if i == len(l_list) - 1:
            break
        if i != len(l_list):
            i += 1

    return l_list[0] == r_list[0]

Solution

  • I would avoid using a while loop in that case, I think this is a better and more clear solution:

    def remove_same(s1, s2):
        l1 = list(s1)
        l2 = list(s2)
        out1 = []
        out2 = []
        for c1, c2 in zip(l1, l2):
            if c1 != c2:
                out1.append(c1)
                out2.append(c2)
                
        s1_out = "".join(out1)
        s2_out = "".join(out2)
        
        print(s1_out)
        print(s2_out)
    
    

    It could be shortened using some list comprehensions but I was trying to be as explicit as possible