1

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

asked Aug 22, 2022 at 22:55
1
  • 3
    Take a look at difflib Commented Aug 22, 2022 at 22:58

1 Answer 1

2

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

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.