Find the position of difference between two strings

前端 未结 6 1602
别那么骄傲
别那么骄傲 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条回答
  •  梦毁少年i
    2021-01-04 00:13

    Python really comes with batteries included. Have a look at difflib

    >>> import difflib
    >>> a='HELPMEPLZ'
    >>> b='HELPNEPLX'
    >>> s = difflib.SequenceMatcher(None, a, b)
    >>> for block in s.get_matching_blocks():
    ...     print block
    Match(a=0, b=0, size=4)
    Match(a=5, b=5, size=3)
    Match(a=9, b=9, size=0)
    

    difflib is very powerful and a some study of the documentation is really recommended.

提交回复
热议问题