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"?
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 .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.