Edit distance algorithms count the operations needed to turn one string into another. This page covers the seven edit-based calculators in strsimpy 0.5.0. All classes can be imported from the package root, and the historical per-module imports shown here remain supported.
All algorithms operate on Unicode code points, matching Python’s len() and
indexing semantics: an emoji or a CJK character counts as one character.
Overview
| Calculator | Returns | Normalized | Metric | Time |
|---|---|---|---|---|
Levenshtein |
distance | No | Yes | O(m*n) |
NormalizedLevenshtein |
distance and similarity | Yes | No | O(m*n) |
WeightedLevenshtein |
distance | No | No | O(m*n) |
Damerau |
distance | No | Yes | O(m*n) |
OptimalStringAlignment |
distance and alignment | No | No | O(m*n) |
MLIPNS |
binary similarity and distance | Yes | No | O(max(m,n)) |
| Strcmp95 | similarity and distance | Yes | No | O(m*n) |
A distance is 0 for identical strings and grows as strings differ. A
similarity is 1 for identical strings and 0 for completely different ones.
A metric also satisfies the triangle inequality,
d(x, y) <= d(x, z) + d(z, y).
Choosing a calculator
Count simple edits
UseLevenshteinwhen insertions, deletions, and substitutions should all cost one unit.Compare scores across lengths
UseNormalizedLevenshteinto get a distance in[0.0, 1.0]and its complement as a similarity.Model domain-specific costs
UseWeightedLevenshteinwhen some substitutions are cheaper than others, for example OCR confusions or adjacent keyboard keys.Allow adjacent transpositions
UseDameraufor a true metric with adjacent transpositions, orOptimalStringAlignmentwhen the one-edit-per-substring restriction is acceptable.Match product names or Census names
UseMLIPNSor Strcmp95 only for the narrow use cases described below; neither is a general-purpose similarity.
Levenshtein
The Levenshtein distance is the minimum number of single-character insertions,
deletions, and substitutions needed to transform s0 into s1. This
implementation uses the Wagner-Fischer dynamic-programming algorithm with two
rolling rows, so it runs in O(m*n) time and uses O(len(s1)) extra space.
The recurrence is:
d(i, j) = min(
d(i - 1, j) + 1, # deletion
d(i, j - 1) + 1, # insertion
d(i - 1, j - 1) + (s0[i - 1] != s1[j - 1]) # match or substitution
)
d(i, 0) = i
d(0, j) = jfrom strsimpy import Levenshtein
levenshtein = Levenshtein()
print(levenshtein.distance("kitten", "sitting"))
print(levenshtein.distance("flaw", "lawn"))
print(levenshtein.distance("Saturday", "Sunday"))
print(levenshtein.distance("abc", "abc"))3
2
3
0.0The last value is the float 0.0, not the integer 0. Levenshtein distance is
a metric: it is symmetric, zero only for equal strings, and satisfies the
triangle inequality.
Normalized Levenshtein
NormalizedLevenshtein divides the Levenshtein distance by the length of the
longer string, which maps the distance to [0.0, 1.0]. The similarity is the
complement of the distance.
distance(s0, s1) = levenshtein(s0, s1) / max(len(s0), len(s1))
similarity(s0, s1) = 1 - distance(s0, s1)If both strings are empty, the distance is 0.0 and the similarity is 1.0.
from strsimpy import NormalizedLevenshtein
normalized = NormalizedLevenshtein()
print(normalized.distance("kitten", "sitting"))
print(normalized.similarity("kitten", "sitting"))
print(normalized.distance("abc", "abd"))
print(normalized.similarity("abc", "abd"))
print(normalized.distance("", "abc"))
print(normalized.similarity("", ""))0.42857142857142855
0.5714285714285714
0.3333333333333333
0.6666666666666667
1.0
1.0Weighted Levenshtein
WeightedLevenshtein uses the same dynamic program as Levenshtein, but takes
three optional callables that return the cost of each operation. Omitted
callables default to a cost of 1.0.
d(i, j) = min(
d(i - 1, j) + deletion_cost(s0[i - 1]),
d(i, j - 1) + insertion_cost(s1[j - 1]),
d(i - 1, j - 1) + substitution_cost(s0[i - 1], s1[j - 1])
)The callables receive one-character Python strings; the substitution callable
receives the source and target characters. Substituting equal characters always
costs 0.0. Exceptions raised by a cost function propagate to the caller.
from strsimpy import WeightedLevenshtein
def insertion_cost(char):
return 1.0
def deletion_cost(char):
return 1.0
def substitution_cost(char_a, char_b):
if char_a == "t" and char_b == "r":
return 0.5
return 1.0
weighted = WeightedLevenshtein(
substitution_cost_fn=substitution_cost,
insertion_cost_fn=insertion_cost,
deletion_cost_fn=deletion_cost,
)
print(weighted.distance("String1", "String2"))
print(weighted.distance("t", "r"))
print(weighted.distance("tr", "rt"))1.0
0.5
1.5The last value is 1.5: the example gives a discount only to t replaced by
r (0.5), while r replaced by t still costs 1.0. Make the callable
symmetric if both directions should receive the discount.
Insertion and deletion costs can differ too:
weighted = WeightedLevenshtein(
insertion_cost_fn=lambda char: 2.0,
deletion_cost_fn=lambda char: 3.0,
)
print(weighted.distance("", "ab"))
print(weighted.distance("ab", ""))4.0
6.0Damerau-Levenshtein
Damerau implements the unrestricted Damerau-Levenshtein distance with
adjacent transpositions. An operation is an insertion, a deletion, a
substitution, or a transposition of two adjacent characters. Unlike Optimal
String Alignment, no substring is restricted to a single edit. The result is a
metric.
The recurrence is the Levenshtein one plus a transposition term. Let i1 be
the last row before i that contained s1[j - 1], and j1 the last column
before j that contained s0[i - 1]. Then:
d(i, j) = min(
d(i - 1, j) + 1,
d(i, j - 1) + 1,
d(i - 1, j - 1) + (s0[i - 1] != s1[j - 1]),
d(i1 - 1, j1 - 1) + (i - i1 - 1) + 1 + (j - j1 - 1)
)from strsimpy import Damerau
damerau = Damerau()
print(damerau.distance("ABCDEF", "ABDCEF"))
print(damerau.distance("ABCDEF", "BACDFE"))
print(damerau.distance("ABCDEF", "ABCDE"))
print(damerau.distance("CA", "AC"))
print(damerau.distance("ABCDEF", "POIU"))1
2
1
1
6ABCDEF to ABDCEF needs a single adjacent transposition (DC to CD);
ABCDEF to BACDFE needs two. As with Levenshtein, identical inputs return
the float 0.0.
Optimal String Alignment
OptimalStringAlignment implements the restricted Damerau-Levenshtein
distance, also called Optimal String Alignment (OSA). It adds a transposition
recurrence to Levenshtein, but with the restriction that no substring may be
edited more than once. This makes it cheaper to reason about than the
unrestricted variant, but it is not a metric.
d(i, j) = min(
d(i - 1, j) + 1,
d(i, j - 1) + 1,
d(i - 1, j - 1) + (s0[i - 1] != s1[j - 1])
)
if i > 1 and j > 1
and s0[i - 1] == s1[j - 2]
and s0[i - 2] == s1[j - 1]:
d(i, j) = min(d(i, j), d(i - 2, j - 2) + 1)from strsimpy import OptimalStringAlignment
osa = OptimalStringAlignment()
print(osa.distance("CA", "ABC"))
print(osa.alignment("CA", "ABC"))
print(osa.distance("CA", "AC"))
print(osa.alignment("CA", "AC"))
print(osa.distance("AC", "ABC"))3
[('delete', 'C', ''), ('insert', '', 'B'), ('insert', '', 'C')]
1
[('transpose', 'CA', 'AC')]
1alignment() returns the edit script behind the score as
(op, source, target) tuples in application order. The operation is one of
insert, delete, substitute, or transpose. Insertions have an empty
source string; deletions have an empty target string; a transposition carries
the two adjacent source characters and the two target characters. The number of
tuples always equals distance(s0, s1).
MLIPNS
MLIPNS (Modified Language-Independent Product Name Search) is a binary
similarity measure from product-name matching (Shannaq and Alexandrov, 2010).
It compares strings with a Hamming-style mismatch count that tolerates
different lengths, then forgives a bounded number of mismatches. The result is
always exactly 0.0 or 1.0, and distance is 1 - similarity.
The defaults are threshold=0.25 and max_mismatches=2. First the algorithm
counts mismatches over the overlapping prefix plus the length difference and
computes:
mismatch_ratio = ham / maxlenIt accepts the pair when mismatch_ratio <= threshold. Otherwise it runs up to
max_mismatches extra rounds; each round forgives one mismatch by decrementing
both ham and maxlen by one, then checks the ratio again. If maxlen
reaches 0, the pair is accepted as well; this is another reason very short
inputs are treated permissively. The two inputs are always compared
symmetrically.
from strsimpy import MLIPNS
mlipns = MLIPNS()
print(mlipns.similarity("abcg", "abcdeg"))
print(mlipns.similarity("abcg", "abcdefg"))
print(mlipns.similarity("ab", "cd"))
print(mlipns.similarity("abcd", "wxyz"))
print(mlipns.distance("ab", "cd"))1.0
0.0
1.0
0.0
0.0The constructor accepts the threshold and the number of extra rounds:
print(MLIPNS(threshold=0.5, max_mismatches=2).similarity("abcg", "abcdefg"))
print(MLIPNS(threshold=0.0, max_mismatches=2).similarity("abcg", "abcdefg"))1.0
0.0Strcmp95
Strcmp95 is the string comparison routine used by the US Census Bureau
(Winkler, 1990). It is a Jaro-Winkler variant that grants partial credit for
character pairs that are common OCR or phonetic confusions (0/O, 1/I,
A/E, B/V, and others).
Both inputs are stripped of surrounding Python-style whitespace and uppercased
before comparison. The result lies in [0.0, 1.0], and distance is
1 - similarity. The main weight is computed as:
num_sim = num_com + 0.3 * n_simi
weight = (num_sim / len(s0) + num_sim / len(s1)
+ (num_com - n_trans) / num_com) / 3Here num_com is the number of exact character matches, n_simi counts
confusion-table pairs, and n_trans is the number of transpositions. When
weight > 0.7, an up-to-four-character common-prefix boost is applied unless
the first character is an ASCII digit:
weight += min(0.1, 1 / max_len) * prefix * (1 - weight)from strsimpy.strcmp95 import StrCmp95
strcmp = StrCmp95()
print(strcmp.similarity("MARTHA", "MARHTA"))
print(strcmp.similarity("DWAYNE", "DUANE"))
print(strcmp.similarity("DIXON", "DICKSONX"))
print(strcmp.similarity(" martha ", "marhta"))
print(strcmp.distance("MARTHA", "MARHTA"))0.9611111111111111
0.873
0.8393333333333334
0.9611111111111111
0.03888888888888886The padded lowercase input scores the same as the uppercase one because normalization happens first.
Confusion-table partial credit
Partial credit only applies when at least one exact match already exists, and
only to characters in the ASCII range used by the original C implementation.
Without an exact match, the similarity is 0.0 even if the confusion table
contains the pair:
print(strcmp.similarity("O", "0"))
print(strcmp.similarity("A0", "AO"))0.0
0.7899999999999999"A0" and "AO" share an exact A, so the 0/O pair earns partial credit
for a score of approximately 0.79.
Long-string option
Pass long_strings=True to enable the extra long-string adjustment from the
original algorithm. The default is False.
default = StrCmp95()
long_strings = StrCmp95(long_strings=True)
print(default.similarity("abcdefghiX", "abcdefghij"))
print(long_strings.similarity("abcdefghij", "abcdefghiX"))
print(long_strings.long_strings)0.96
0.9714285714285714
TrueUnicode caveat
Non-ASCII characters can still match exactly, but they never receive
confusion-table credit. Uppercasing is applied per code point with Rust’s
Unicode tables, which may differ from Python’s str.upper() for a handful of
exotic code points; common cases such as ß to SS behave identically.
print(strcmp.similarity("Ä", "A"))
print(strcmp.similarity("ß", "SS"))
print(strcmp.similarity("上海", "上每"))0.0
1.0
0.6666666666666666Related
- Sequence similarity algorithms: Jaro-Winkler, longest common subsequence, Metric LCS, and Ratcliff-Obershelp.
- Sequence alignment: raw alignment scores from Needleman-Wunsch, Smith-Waterman, and Gotoh.
- Shingle-based algorithms: n-gram, Q-Gram, and set-based measures.
- Token-based algorithms: Bag distance and Monge-Elkan.
- Algorithms overview
- Compatibility guide: differences from TextDistance and java-string-similarity.