Strings
Loading
Loading
Strings
Transform input into a canonical form so the comparison becomes trivial.
By the end of this chapter
When a rule says two things are equivalent under some transformation — ignoring case, ignoring punctuation, ignoring order — apply the transformation first. What remains is an equality check.
"Ada_Lovelace 01" vs "adalovelace01""Ada_Lovelace 01"drop non-alphanumerics"AdaLovelace01"lowercase"adalovelace01"now a plain equalityequal| Rule | Canonical form |
|---|---|
| Ignore case | lowercase everything |
| Ignore order of characters | sort the characters |
| Ignore punctuation and spacing | keep only alphanumerics |
| Ignore leading zeros | parse to a number |
Building transformed copies costs O(n) memory. When the transformation is a per-character decision that does not depend on neighbours, you can skip characters in place instead.
def same_ignoring_noise(a, b): i = j = 0 while i < len(a) and j < len(b): if not a[i].isalnum(): i += 1 continue if not b[j].isalnum(): j += 1 continue if a[i].lower() != b[j].lower(): return False i += 1 j += 1 # Trailing noise on either side must also be skipped. while i < len(a) and not a[i].isalnum(): i += 1 while j < len(b) and not b[j].isalnum(): j += 1 return i == len(a) and j == len(b)Sign in to keep a note here. It is free, and nobody else can see it.
Sign inWhat this chapter was for:
Before moving on: try 2 practice problems.