Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the position of difference between two strings

Tags:

python

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 positions 4 and 8.

like image 410
Linus Svendsson Avatar asked Dec 17 '11 14:12

Linus Svendsson


People also ask

How do you find the difference between two strings?

You can use StringUtils. difference(String first, String second).

How do you find the difference between two strings in Python?

Use the == and != operators to compare two strings for equality. Use the is operator to check if two strings are the same instance. Use the < , > , <= , and >= operators to compare strings alphabetically.

How do you find the position of a string?

The indexOf() method returns the position of the first occurrence of specified character(s) in a string. Tip: Use the lastIndexOf method to return the position of the last occurrence of specified character(s) in a string.


3 Answers

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.

like image 194
Óscar López Avatar answered Oct 05 '22 20:10

Óscar López


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.

like image 36
Fredrik Pihl Avatar answered Oct 05 '22 19:10

Fredrik Pihl


>>> from itertools import izip
>>> s1 = 'HELPMEPLZ'
>>> s2 = 'HELPNEPLX'
>>> [i for i,(a1,a2)  in enumerate(izip(s1,s2)) if a1!=a2]
[4, 8]
like image 33
ovgolovin Avatar answered Oct 05 '22 20:10

ovgolovin