Python Find the Difference Between Two Strings
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
)
(
differences
)
Code analysis:
import difflib: Import thedifflibmodule, which provides tools for comparing sequences.differ = difflib.Differ(): create aDifferobject used to compare two strings.diff = differ.compare(str1.splitlines(), str2.splitlines()): When usingDifferobject'scomparemethod to compare each line of the two strings.splitlines()The method splits a string into a list of lines.return 'n'.join(diff): Join the comparison results into a string and return it.str1andstr2: Define the two strings to compare.differences = find_string_differences(str1, str2): Callingfind_string_differencesfunction to get the difference between the two strings.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.。
Python3 Examples