This might not apply for all cases, but if you would like to compare characters you can use set
:
a = "word"
b = "wind"
diff = set.intersection(set(a),set(b))
print(len(diff))
>> 2
This ignores sequences as you are grouping them into a set of unique characters.
Another interesting Python standard module library you can use is difflib
.
from difflib import Differ
d = Differ()
a = "word"
b = "wind"
[i for i in d.compare(a,b) if i.startswith('-')]
>>['- o', '- r']
difflib
essentially provides methods for you to compare sequences such as strings. From the Differ
object above, you can compare 2 strings and identify characters which are added or removed to track changes from the string a
to string b
. In the example given, a list comprehension is used to filter out characters which are removed from a
to b
, you can also check characters that start with +
for characters that are added.
[i for i in d.compare(a,b) if i.startswith('+')]
>>['+ i', '+ n']
Or characters common to both sequence addressing
How to check how many characters a variable has in common with another
variable
common = [i for i in d.compare(a,b) if i.startswith(' ')]
print(common, len(common))
>> [' w', ' d'] 2
You can read more about the Differ
object here