Python - getting just the difference between strings

后端 未结 6 2132
心在旅途
心在旅途 2021-01-12 08:12

What\'s the best way of getting just the difference from two multiline strings?

a = \'testing this is working \\n testing this is working 1 \\n\'
b = \'testi         


        
6条回答
  •  萌比男神i
    2021-01-12 08:38

    You could use the following function:

    def __slave(a, b):
    
        for i, l_a in enumerate(a):
            if b == l_a:
                return i
        return -1
    
    def diff(a, b):
    
        t_b = b
        c_i = 0
        for c in a:
    
            t_i = __slave(t_b, c)
            if t_i != -1 and (t_i > c_i or t_i == c_i):
                c_i = t_i
                t_b = t_b[:c_i] + t_b[c_i+1:]
    
        t_a = a
        c_i = 0
        for c in b:
    
            t_i = __slave(t_a, c)
            if t_i != -1 and (t_i > c_i or t_i == c_i):
                c_i = t_i
                t_a = t_a[:c_i] + t_a[c_i+1:]
    
        return t_b + t_a
    

    Usage sample print diff(a, b)

提交回复
热议问题