Overview
Using the operations replace, delete, insert and equal a sequence s1 can be transformed into another sequence s2.
The get_opcodes() returns the required number of operations to transform one sequence into another as a list of tuples. Each tuple contains one opcode.
- Each tuple consists of the following information:
An opcode describing the operation to be performed on the substring of sequence – s1. An opcode assumes one of the following values ‘replace’, ‘delete’, ‘insert’ and ‘equal’. - The start index of the substring of sequence s1
- The end index of the substring of sequence s1
- The start index of the substring of sequence s2
- The end index of the substring of sequence s2
In Python, a substring of s is denoted as string[start:end] where start index is included in the substring and the end index is not included in the substring.
Example
# Example Python program that gets the opcodes
# to make sequence1 into sequence2 using the
# get_opcodes() method of the SequenceMatcher object
import difflib
# The sequences
string1 = "Humpty Dumpty sat on a wall"
string2 = "Humpty Dumpty had a great fall"
# Create a SequenceMatcher object
seqMatcher = difflib.SequenceMatcher()
# Set the sequences to the SequenceMatcher
seqMatcher.set_seq1(string1)
seqMatcher.set_seq2(string2)
# Get the opcodes
opCodes = seqMatcher.get_opcodes()
print("The opcodes to turn string1 into string2:")
print(opCodes)Output
The opcodes to turn string1 into string2:
[('equal', 0, 14, 0, 14), ('replace', 14, 15, 14, 23), ('equal', 15, 18, 23, 26), ('replace', 18, 24, 26, 27), ('equal', 24, 27, 27, 30)]