Something like this?

a = "abcde"
b = "ab2de"

for index, char in enumerate(a):
    if not b[index] == char:
        print(f"First mismatch on index {index}: {char} is not {b[index]}")

Would print: First mismatch on index 2: c is not 2

Another possibility would be to create a list of 3-way-tuples, where the first element would be the index, the second element would be the char in a and the third element would be the char in b:

a = "abcde"
b = "ab23e"
print([(index, char, b[index]) for index, char in enumerate(a) if not b[index] == char])

Would result in [(2, 'c', '2'), (3, 'd', '3')]

Answer from JarroVGIT on Stack Overflow
Discussions

Python: Finding the position of the first occurring difference between 2 strings. (Unequal lengths) - Stack Overflow
I have been trying to solve this past final exam question. I think I am getting close, but due to the unequal lengths of the two strings, I am getting an index out of range error which i can't figu... More on stackoverflow.com
🌐 stackoverflow.com
Python - difference between two strings - Stack Overflow
For example I have word afrykanerskojęzyczny and many of words like afrykanerskojęzycznym, afrykanerskojęzyczni, nieafrykanerskojęzyczni. What is the effective (fast and giving small diff size) solution to find difference between two strings and restore second string from the first one and diff? More on stackoverflow.com
🌐 stackoverflow.com
Comparing two strings and returning the difference. Python 3 - Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most. Learn more about Collectives ... Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... Closed 10 years ago. My goal is to write a program which compares two strings and displays the difference between the first ... More on stackoverflow.com
🌐 stackoverflow.com
python - Finding differences between strings - Stack Overflow
I have the following function that gets a source and a modified strings, and bolds the changed words in it. def appendBoldChanges(s1, s2): "Adds tags to words that are chan... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Reddit
reddit.com › r/learnpython › how to find the difference between two strings.
r/learnpython on Reddit: how to find the difference between two strings.
August 24, 2021 -

hello friends !

so i have a question in where there are 2 strings

    string_1 = "This is the first sentence"
    string_2 = "And this is the second sentence"

i am trying to find words that are in 1 string thats not in another so the answer to this one will be something like:

    ['This', 'first', 'And', 'this', 'second']

so this was what i did. it might be janky but i just wanted to try it out myself before i asked around.

    string_1 = string_1.split()
    string_2 = string_2.split()
    list(set(string_1).difference(string_2))

however, my output is this:

    ['first', 'This']

im not really sure as to why itsshowing just these values and not the rest. can someone tell me where i made a mistake perhaps please ?

i was using this as a reference

Top answer
1 of 7
185

You can use ndiff in the difflib module to do this. It has all the information necessary to convert one string into another string.

A simple example:

import difflib

cases=[('afrykanerskojęzyczny', 'afrykanerskojęzycznym'),
       ('afrykanerskojęzyczni', 'nieafrykanerskojęzyczni'),
       ('afrykanerskojęzycznym', 'afrykanerskojęzyczny'),
       ('nieafrykanerskojęzyczni', 'afrykanerskojęzyczni'),
       ('nieafrynerskojęzyczni', 'afrykanerskojzyczni'),
       ('abcdefg','xac')] 

for a,b in cases:     
    print('{} => {}'.format(a,b))  
    for i,s in enumerate(difflib.ndiff(a, b)):
        if s[0]==' ': continue
        elif s[0]=='-':
            print(u'Delete "{}" from position {}'.format(s[-1],i))
        elif s[0]=='+':
            print(u'Add "{}" to position {}'.format(s[-1],i))    
    print()      

prints:

afrykanerskojęzyczny => afrykanerskojęzycznym
Add "m" to position 20

afrykanerskojęzyczni => nieafrykanerskojęzyczni
Add "n" to position 0
Add "i" to position 1
Add "e" to position 2

afrykanerskojęzycznym => afrykanerskojęzyczny
Delete "m" from position 20

nieafrykanerskojęzyczni => afrykanerskojęzyczni
Delete "n" from position 0
Delete "i" from position 1
Delete "e" from position 2

nieafrynerskojęzyczni => afrykanerskojzyczni
Delete "n" from position 0
Delete "i" from position 1
Delete "e" from position 2
Add "k" to position 7
Add "a" to position 8
Delete "ę" from position 16

abcdefg => xac
Add "x" to position 0
Delete "b" from position 2
Delete "d" from position 4
Delete "e" from position 5
Delete "f" from position 6
Delete "g" from position 7
2 of 7
58

I like the ndiff answer, but if you want to spit it all into a list of only the changes, you could do something like:

import difflib

case_a = 'afrykbnerskojęzyczny'
case_b = 'afrykanerskojęzycznym'

output_list = [li for li in difflib.ndiff(case_a, case_b) if li[0] != ' ']
🌐
Iditect
iditect.com › faq › python › find-the-position-of-difference-between-two-strings-in-python.html
Find the position of difference between two strings in python
The find_first_difference_position function will return the position of the first difference between the two strings or the length of the shorter string if there are no differences.
🌐
Javatpoint
javatpoint.com › python-program-to-find-difference-between-two-strings
Python Program to Find Difference between Two Strings - Javatpoint
Python Program to Find Difference between Two Strings with Python with python, tutorial, tkinter, button, overview, canvas, frame, environment set-up, first python program, operators, etc.
Find elsewhere
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-string-comparison
Python Compare Strings: Methods, Operators & Best Practices | DigitalOcean
June 15, 2026 - Learn how to compare strings in Python using ==, is, and ordering operators, plus casefold() and difflib for tricky cases.
🌐
CodePal
codepal.ai › code-generator › query › cCafnfTQ › python-function-find-first-differing-character
Python Function: Find First Differing Character - CodePal
A Python function called first_diff that finds the first location where two strings differ. If the strings are identical, it returns -1.
🌐
Exponent
tryexponent.com › courses › swe-practice › diff-between-two-strings
List the Difference Between Two Strings - Exponent
February 19, 2025 - from typing import List from functools import cache @cache def solve(X: str, Y: str) -> List[str]: if not X: return ["+" + y for y in Y] if not Y: return ["-" + x for x in X] output = [] if X[0] == Y[0]: return [X[0]] + solve(X[1:], Y[1:]) else: o1 = solve(X[1:], Y) o2 = solve(X, Y[1:]) if len(o1) > len(o2): return ["+" + Y[0]] + o2 else: return ["-" + X[0]] + o1 def diff_between_two_strings(source: str, target: str) -> List[str]: return solve(source, target)
🌐
Quora
quora.com › How-do-you-find-the-difference-between-two-strings-in-python-I-have-to-translate-this-sentence-twice-and-find-the-error-in-the-translation-by-comparing-the-two-strings-and-returning-the-number-of-errors
How to find the difference between two strings in python? I have to translate this sentence twice and find the error in the translation by comparing the two strings and returning the number of errors - Quora
Answer (1 of 4): How do you find the difference between two strings in python? First. I would break up the two strings into word tokens. This can be done using Python’s [code ]re.split()[/code] method to break up on non-word boundaries [code ]r'\W+'[/code]. The sentences are now lists of words....
🌐
Educative
educative.io › answers › how-to-return-the-difference-of-two-strings-in-python
How to return the difference of two strings in Python
Let’s define the difference() function that takes two strings as parameters. ... Line 1: We define a function named difference() that takes in two strings to find the uncommon words between ...
🌐
Miguendes
miguendes.me › python-compare-strings
How to Compare Two Strings in Python (in 8 Easy Ways)
July 2, 2022 - Learn to compare if two strings are equal, or similar. Take string difference. Make comparisons ignoring case, and check if they are almost equal.
🌐
Techie Delight
techiedelight.com › home › string › find difference between two strings
Find difference between two strings | Techie Delight
September 10, 2025 - A simple solution is to store the count of each character of the second string in a map. Then, for each character in the first string, decrease its count. If the count of any character becomes negative at any point in time, we can say that the ...
🌐
Towards Data Science
towardsdatascience.com › home › latest › side-by-side comparison of strings in python
Side-by-side comparison of strings in Python | Towards Data Science
March 5, 2025 - Due to its recursive nature, execution time can become quadratic, depending on the amount of differences in the sequences. For our goal, this performance is acceptable. It will not be used to compare books of texts, but only a few lines at a time. In order to match sequences we first have to create an instance of the SequenceMatcher class. The constructor takes the two sequences to match as parameters a and b. The parameters for junk detection are not used. When passing strings as arguments, a string is seen as a sequence of characters.
🌐
Towards Data Science
towardsdatascience.com › home › latest › “find the difference” in python
"Find the Difference" in Python | Towards Data Science
January 21, 2025 - In Python, we can easily implement something very similar using the Difflib with a single line of code. The first function I’m going to show off is context_diff(). Let’s make up two lists with some string elements.
🌐
GitHub
github.com › xiaomei7 › Coursera_Introduction_to_Scripting_in_Python › blob › master › PDR_final_project › PDR_final_project.py
Coursera_Introduction_to_Scripting_in_Python/PDR_final_project/PDR_final_project.py at master · xiaomei7/Coursera_Introduction_to_Scripting_in_Python
lines2 - list of single line strings · Output: Returns a tuple containing the line number (starting from 0) and · the index in that line where the first difference between lines1 · and lines2 occurs. · Returns (IDENTICAL, IDENTICAL) if the two lists are the same. """ # find out the length of the two lists ·
Author   xiaomei7