Find the position of difference between two strings

前端 未结 6 1601
别那么骄傲
别那么骄傲 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:28

    Try this:

    s1 = 'HELPMEPLZ'
    s2 = 'HELPNEPLX'
    [i for i in xrange(len(s1)) if s1[i] != s2[i]]
    

    It will return:

    > [4, 8]
    

    The above solution will return a list with the indexes in sorted order, won't create any unnecessary intermediate data structures and it will work on Python 2.3 - 2.7. For Python 3.x replace xrange for range.

提交回复
热议问题