Python Find the Difference Between Two Strings

Document 对象参考手册Python3 Examples

In Python, we can usedifflibmodule to compare two strings and find the differences between them.difflibThe module provides aDifferclass that can compare two strings line by line and generate a difference report.

The following is example code showing how to usedifflibto find the differences between two strings:

Example

import difflib

def find_string_differences(str1, str2):
    differ = difflib.Differ()
    diff = differ.compare(str1.splitlines(), str2.splitlines())
    return 'n'.join(diff)

str1 = """Hello world!
This is a test.
Python is fun."""


str2 = """Hello world!
This is a test.
Python is awesome."""


differences = find_string_differences(str1, str2)
print(differences)

Code analysis:

  1. import difflib: Importdifflibmodule, which provides tools for comparing sequences.
  2. differ = difflib.Differ(): Create aDifferobject to compare two strings.
  3. diff = differ.compare(str1.splitlines(), str2.splitlines()): UseDifferobject'scomparemethod to compare each line of the two strings.splitlines()method splits the string into a list by lines.
  4. return 'n'.join(diff): Join the comparison results into a string and return it.
  5. str1andstr2: Define two strings to compare.
  6. differences = find_string_differences(str1, str2): Callfind_string_differencesfunction to get the differences between the two strings.
  7. print(differences): Print the difference result.

Output result:

  Hello world!
  This is a test.
- Python is fun.
+ Python is awesome.

In the output result,-indicates the content in the first string,+indicates the content in the second string. In this example,Python is fun.is replaced byPython is awesome.。

Document 对象参考手册Python3 Examples

Other Extensions