HappiomHappiom
  • Self-Improvement
  • Relationship
  • AI for Life
  • Apps
  • Tech
  • More
    • Online Diary
    • Glossary
  • Learn
    • Book
    • >> Soft Skills
    • Time Management
    • >> Tech Skills
    • R
    • Linux
    • Python
  • Our Apps
    • Download Diary App
    • Write Your First Diary
    • Login to Online Diary App
    • 100K+ Famous Quotes Site
  • Resources
    • Self-Improvement Guide
      • 21-Days to Self-Improvement
      • Creating a Habit
      • Learn Life Experiences
      • Easily Prioritizing Tasks
      • Learning from Mistakes
      • Doing Regular Exercises
      • Setting Priority for Success
      • Avoiding Common Mistakes
      • Eating Healthy Food Regularly
    • Journaling Guide
      • Online Diary
      • Best Diary Apps
      • Diary Writing Ideas
      • Diary Writing Topics
      • Avoid Writing in Diary
      • Diary Writing as Hobby
      • Reasons to Write a Diary
      • Types of Feelings In Diary
      • Improve Diary Writing Skills
  • Self-Improvement
  • Relationship
  • AI for Life
  • Apps
  • Tech
  • More
    • Online Diary
    • Glossary
  • Learn
    • Book
    • >> Soft Skills
    • Time Management
    • >> Tech Skills
    • R
    • Linux
    • Python
  • Our Apps
    • Download Diary App
    • Write Your First Diary
    • Login to Online Diary App
    • 100K+ Famous Quotes Site
  • Resources
    • Self-Improvement Guide
      • 21-Days to Self-Improvement
      • Creating a Habit
      • Learn Life Experiences
      • Easily Prioritizing Tasks
      • Learning from Mistakes
      • Doing Regular Exercises
      • Setting Priority for Success
      • Avoiding Common Mistakes
      • Eating Healthy Food Regularly
    • Journaling Guide
      • Online Diary
      • Best Diary Apps
      • Diary Writing Ideas
      • Diary Writing Topics
      • Avoid Writing in Diary
      • Diary Writing as Hobby
      • Reasons to Write a Diary
      • Types of Feelings In Diary
      • Improve Diary Writing Skills
Expand All Collapse All
  • Python Examples
    • Basic Syntax
      • Python Example Code to Concat 2 Numbers
      • Python Example Code to Concat N Strings
      • Python Code to Find Perimeter of a Circle
      • Python Code to Convert CSV file to Parquet format
      • Python Code to Get Current Day of Week
      • Python Code to Convert Binary String to Decimal Number Vice versa
      • Python Code to Find Difference Between 2 Strings
      • Python Example Code to Remove Duplicates from a List
      • Python Example Code to Calculate Height of Triangle
      • Python Code to Generate Complex Random Password
    • File Handling
      • Python Code to Write & Read Key Value Pair in File
      • In Python File is Not Opening (How to Fix)
      • Python Code to Read Specific Line from a File
      • Python Code to Clear Contents of a File
      • Python Code to Count and List Files in a Directory
    • Modules and Libraries
      • Python Code for Automation using BDD
      • Python Code to Load .SO File (and Invoke a Function)
    • Object-Oriented Programming
      • Python Code to Create a Class with Attributes
      • Python Code to Define Methods in a Class
    • Python Example Code to Check Internet Connection
    • Example Python Code to Send an Email
    • Python Code to Fetch Data from an API (e.g., OpenWeatherMap)
    • Example Python Code to Extract Text from PDF
    • Python Code to Perform Web Scraping (e.g., Scraping Wikipedia)
    • Example Python Code to Plot Data Using Matplotlib
    • Python Code to Perform Data Analysis with Pandas
    • Example Python Code to Train a Simple Machine Learning Model (e.g., Linear Regression)
    • Python Code to Handle User Authentication in Flask
    • Example Python Code to interact with databases using libraries like SQLAlchemy

Python Code to Find Difference Between 2 Strings

Let’s Learn efficient techniques to determine whether two strings are identical and how to summarize their variances.

First, I’ll start with a simplified string comparison example and then do a detailed comparison which summarizes the string differences along with their locations.

Simple String Difference

Let me write a simple Python function that checks whether two strings are the same or different.

def compare_strings(str1, str2):
    if str1 == str2:
        return "The strings are the same."
    else:
        return "The strings are different."

# Example shows calling the above function
str1 = "kitten"
str2 = "sitting"
print(compare_strings(str1, str2))

Output:

The strings are the different.

String Difference and Returning True or False

Now I’ll rewrite the code to return True if the strings are the same and False otherwise.

def are_strings_same(str1, str2):
    return str1 == str2

# Example usage:
str1 = "kitten"
str2 = "sitting"
print(are_strings_same(str1, str2))  # Output: False

In this enhanced version of code, the function are_strings_same returns True if str1 is equal to str2, indicating that the strings are the same. It returns False if the strings are different.

Finding String Difference and Summarizing the Differences

Let’s go detailed, now the below code compares the strings, finds the differences and summarizes it for you along with location where the differences are seen.

def summarize_string_differences(str1, str2):
    m = len(str1)
    n = len(str2)
    dp = [[0] * (n + 1) for _ in range(m + 1)]

    for i in range(1, m + 1):
        for j in range(1, n + 1):
            if str1[i - 1] == str2[j - 1]:
                dp[i][j] = dp[i - 1][j - 1] + 1
            else:
                dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])

    i = m
    j = n
    differences = []
    while i > 0 or j > 0:
        if i > 0 and j > 0 and str1[i - 1] == str2[j - 1]:
            i -= 1
            j -= 1
        elif j > 0 and (i == 0 or dp[i][j - 1] >= dp[i - 1][j]):
            differences.append(("+", str2[j - 1], j))
            j -= 1
        else:
            differences.append(("-", str1[i - 1], i))
            i -= 1

    differences.reverse()
    return differences

# Let's use the above function
str1 = "kitten"
str2 = "sitting"
differences = summarize_string_differences(str1, str2)
for op, char, pos in differences:
    print(f"{op} {char} at position {pos}")

The output of the provided code, using the example strings “kitten” and “sitting”, would be as follows:

+ s at position 0
- k at position 0
- i at position 1
- t at position 2
- t at position 3
- e at position 4
+ g at position 6

 

This output summarizes the differences between the strings “kitten” and “sitting”, indicating the operations needed to transform one string into the other. It also shows the position of each character involved in the string transformation.

Let me explain the code in detail:

  1. First, Initialize a matrix dp to track the length of the longest common subsequence between str1 and str2.
  2. Now iterate through dp to backtrack and identify differences between the strings, appending tuples representing operations (+ for insert, – for delete) along with the character and its position.
  3. Reverse the differences list to maintain the correct order and prints each operation along with the character and its position to summarize the differences between the strings.

These are the simplest yet efficient methods of performing string differences and even summarizing the differences in detail.

Related Articles
  • Python Example Code to Calculate Height of Triangle
  • Python Example Code to Remove Duplicates from a List
  • Example Python Code to interact with databases using libraries like SQLAlchemy
  • Python Code to Handle User Authentication in Flask
  • Example Python Code to Train a Simple Machine Learning Model (e.g., Linear Regression)
  • Python Code to Perform Data Analysis with Pandas

No luck finding what you need? Contact Us

Previously
Python Code to Convert Binary String to Decimal Number Vice versa
Up Next
Python Example Code to Remove Duplicates from a List
  • About Us
  • Contact Us
  • Archive
  • Hindi
  • Tamil
  • Telugu
  • Marathi
  • Gujarati
  • Malayalam
  • Kannada
  • Privacy Policy
  • Copyright 2026 Happiom. All Rights Reserved.