I'm looking for an easy way to compare two similar strings and output the difference for instance if I have
"abcdefghijklmnop" and "abcdefghi"
the function would output
"jklmnop"
I need to know how to do this in both php and python
I'm looking for an easy way to compare two similar strings and output the difference for instance if I have
"abcdefghijklmnop" and "abcdefghi"
the function would output
"jklmnop"
I need to know how to do this in both php and python
In PHP. array_diff
compares the first against the second array and returns the difference.
$a1 = str_split('abcdefghijklmnop');
$a2 = str_split('abcdefghi');
echo join('', array_diff($a1, $a2)); // jklmnop
This will work as well.
$s1 = 'abcdefghijklmnop';
$s2 = 'abcdefghi';
echo str_replace(str_split($s2), '', $s1); // jklmnop
This could handle $s2 = 'ghiabcdef';
as well because str_replace()
is fed with an array, not a string.
In Python, you can do:
x = "abcdefghijklmnop"
y = x.replace("abcdefghi", "")
# y now equals "jklmnop"
>>> s1 = "abcdefghijklmnop"
>>> s2 = "abcdefghi"
>>> s1.strip(s2)
'jklmnop'
Python has the difflib
module in its standard library that can be used to do this.
import difflib
s1 = "abcdefghijklmnop"
s2 = "abcdefghi"
s = difflib.SequenceMatcher(s1, s2)
for block in s.get_matching_blocks():
print "match of length %d at a[%d] and b[%d]" % block
difflib
is very powerful and has many different ways of searching for differences. Some study of the documentation would be worthwhile if you choose to use this.
In Python:
>>> s1 = 'abcdefghijklmnop'
>>> s2 = 'abcdefghi'
>>> set(s1) - set(s2)
set(['k', 'j', 'm', 'l', 'o', 'n', 'p'])
In Python:
string1 = "abcdefghijklmnop"
string2 = "abcdefghi"
def stringComp(string1, string2):
if len(string1.split(string2)) > 0:
if string1 == string1.split(string2)[0]:
finalstring = stringComp(string2, string1)
else:
finalstring = ''.join(string1.split(string2))
else:
finalstring = ""
return finalstring
This should always give you the difference in the strings. However, I'm sure there is a much easier way to do this.