Find the position of difference between two strings

前端 未结 6 1609
别那么骄傲
别那么骄傲 2021-01-04 00:08

I have two strings of equal length, how can I find all the locations where the strings are different?

For example, \"HELPMEPLZ\" and \"HELPNEPLX\" are different at p

6条回答
  •  渐次进展
    2021-01-04 00:10

    If you store the two strings in a and b, you can loop through all the items and check for inequality.

    python interactive interpreter:

    >>> for i in range(len(a)):
    ...   if a[i] != b[i]: print i, a[i], b[i]
    ... 
    4 M N
    8 Z X
    

    Another way to do this is with list comprehensions. It's all in one line, and the output is a list.

    >>> [i for i in range(len(a)) if a[i] != b[i]]
    [4, 8]
    

    That makes it really easy to wrap into a function, which makes calling it on a variety of inputs easy.

    >>> def dif(a, b):
    ...     return [i for i in range(len(a)) if a[i] != b[i]]
    ...
    >>> dif('HELPMEPLZ', 'HELPNEPLX')
    [4, 8]
    >>> dif('stackoverflow', 'stacklavaflow')
    [5, 6, 7, 8]
    

提交回复
热议问题