3

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"?

utlthpjh
  • 41
  • 4

1 Answers1

3

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.

RobinFrcd
  • 4,439
  • 4
  • 25
  • 49