Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Find the Difference Between Two Strings

Python Find the Difference Between Two Strings

Document Object Reference Manual Python3 Examples

In Python, we can use difflib module to compare two strings and find the differences between them.difflib The module provides a Differ class that compares two strings line by line and generates a difference report.

The following example code shows how to use difflib to find the difference 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: Import the difflib module, which provides tools for comparing sequences.
  2. differ = difflib.Differ(): create a Differ object used to compare two strings.
  3. diff = differ.compare(str1.splitlines(), str2.splitlines()): When using Differ object's compare method to compare each line of the two strings.splitlines() The method splits a string into a list of lines.
  4. return 'n'.join(diff): Join the comparison results into a string and return it.
  5. str1 and str2: Define the two strings to compare.
  6. differences = find_string_differences(str1, str2): Calling find_string_differences function to get the difference 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,- indicates content from the first string,+ indicates content from the second string. In this example,Python is fun. was replaced by Python is awesome.。

Document Object Reference Manual Python3 Examples