I've got two strings like this:
string1 = "Foo Bar"
string2 = "Foo BBar"
How do I compare them to see the difference? If I just compare string1[i]
to string2[i]
I just end up with the last Word "Bar" being different, as, for example, string1[5]
isn't the same as string2[5]
, and so on.
Is there a way to just output "B"?
1 Answer 1
As suggested by @barmar, difflib
may be the way to go here.
So here's a snippet just to fit your example, but it may not be suited for all your cases.
import difflib
string1 = "Foo Bar"
string2 = "Foo BBar"
[d[2:] for d in difflib.ndiff(string1, string2) if d.startswith("+")]
# ['B']
If you want to know more about it, please read the doc or this answer.
answered Aug 22, 2022 at 23:11
Comments
lang-py
difflib