String similarity metrics in Python
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
String similarity is not one problem with one metric. Matching person names, deduplicating product titles, and comparing full documents all reward different notions of "similar." Python has good tools for edit distance, token overlap, phonetic matching, and vector-space similarity, but choosing the wrong metric can be worse than using none at all.
Edit Distance for Small Character-Level Differences
If you care about typos, insertions, deletions, or substitutions, start with edit distance. A practical Python option is rapidfuzz, which is fast and easy to use.
Use character-level metrics when:
- the strings are short
- order matters
- spelling mistakes are common
This works well for names, SKUs, or lightly noisy labels. It is less useful for long documents where token structure matters more than small character edits.
Token-Based Similarity for Word Reordering
If the same words appear in different order, token-based metrics are usually better than raw edit distance.
token_sort_ratio helps when the words are the same but reordered. token_set_ratio is useful when one string contains most of the other plus extra words.
These metrics are common in search normalization and catalog matching.
Jaccard Similarity for Set Overlap
When you only care about overlap between token sets, Jaccard similarity is simple and interpretable.
Jaccard ignores repeated words and character-level typos. That makes it poor for misspellings but useful for rough token overlap.
Cosine Similarity for Longer Text
For sentences or documents, a vector-space approach is often more useful. A simple baseline is TF-IDF plus cosine similarity.
This is better for document-level comparison than plain edit distance because it focuses on shared terms and their relative importance.
Phonetic Matching for Names
If your data contains names that sound similar but are spelled differently, phonetic methods can help. They are not universal, but they can be useful in address books, genealogy, or customer records.
The point is not that phonetic codes are perfect. It is that they solve a different problem than edit distance does.
Choosing the Right Metric
A useful decision guide:
- typo-heavy short strings: Levenshtein-style metrics
- reordered product titles: token sort or token set metrics
- word-overlap heuristics: Jaccard
- document similarity: TF-IDF plus cosine
- names with pronunciation variation: phonetic matching
In real systems, teams often combine two stages. For example, candidate generation might use TF-IDF, and final ranking might use a token-based fuzzy score.
Common Pitfalls
- Using one metric for every text-matching problem.
- Applying character edit distance to long documents.
- Ignoring normalization such as lowercasing, punctuation removal, or Unicode cleanup.
- Treating similarity scores from different metrics as directly comparable.
- Forgetting that domain-specific rules often matter more than the metric itself.
Summary
- String similarity depends on what kind of difference you care about.
- Edit distance is good for typos and short strings.
- Token-based metrics handle reordered phrases better.
- Cosine similarity is a stronger baseline for longer text.
- Phonetic methods are useful for name-like data.
Related reading
- String to Dictionary in Python
- Strip HTML from strings in Python
- Stripping everything but alphanumeric chars from a string in Python
- str.startswith with a list of strings to test for
- Subclass in type hinting
- Substitute multiple whitespace with single whitespace in Python
- Subtract one month from Datetime.Today
- subtuples for a tuple
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.