Python - getting just the difference between strings

后端 未结 6 2091
心在旅途
心在旅途 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条回答
  •  再見小時候
    2021-01-12 08:29

    The easiest Hack, credits @Chris, by using split().

    Note : you need to determine which is the longer string, and use that for split.

    if len(a)>len(b): 
       res=''.join(a.split(b))             #get diff
    else: 
       res=''.join(b.split(a))             #get diff
    
    print(res.strip())                     #remove whitespace on either sides
    

    # driver values

    IN : a = 'testing this is working \n testing this is working 1 \n' 
    IN : b = 'testing this is working \n testing this is working 1 \n testing this is working 2'
    
    OUT : testing this is working 2
    

    EDIT : thanks to @ekhumoro for another hack using replace, with no need for any of the join computation required.

    if len(a)>len(b): 
        res=a.replace(b,'')             #get diff
    else: 
        res=b.replace(a,'')             #get diff
    

提交回复
热议问题