How to compare strings while ignoring formatting differences
Compare two strings by meaning rather than formatting: handle case, whitespace, Unicode normalization, styled characters, reversed text and invisible characters.
Two strings can look identical on screen and still fail an equality check. They can also look different, in bold Unicode letters, mixed case or extra spaces, and still say the same thing. Comparing strings while ignoring formatting means choosing which differences count and normalizing both inputs the same way before you compare them. This guide explains what each kind of formatting difference actually is, which normalization step handles it, and where each step can go wrong.
What "formatting" changes in a string
Before you pick a comparison method, identify which layer the difference lives in. Some formatting changes the stored characters. Some changes only how the characters are displayed. A string comparison only sees the stored characters, so these cases behave very differently.
- Case and whitespace: "Hello World" and "hello world" differ in stored characters (capital letters, a doubled space, possibly tabs or different line endings such as CRLF versus LF).
- Unicode composition: an accented letter like é can be stored as one precomposed code point or as e followed by a combining accent. Both render the same but compare as unequal unless normalized.
- Unicode character substitution: "font generator" and styled-text tools usually replace ordinary letters with different code points, such as Mathematical Bold or fullwidth letters. The output looks like styled text but is a different character sequence.
- CSS presentation: bold, italics, text-transform: uppercase or a CSS mirror effect change only the display. The underlying text is unchanged, so a comparison of the source text is unaffected.
- Character-order reversal: reversed text stores the characters in the opposite order. It is a real change to the string, not a display effect.
- Visual mirroring and upside-down text: the term "mirror text" is ambiguous. It may mean CSS mirroring (display only), reversed order, or substitution with lookalike characters such as turned or rotated letters. Check which one a tool actually produces before deciding how to compare it.
- Bidirectional display and invisible characters: right-to-left marks, override controls, zero-width spaces and similar format characters can change display order or be completely invisible, yet they are stored characters and break exact matches.
How to compare two strings: the basic approach
The reliable pattern is: keep the originals, build a normalized copy of each string using the same steps, and compare the normalized copies. Normalization is for the comparison only; storing or displaying the normalized form can lose information you need later.
Order matters. Unicode normalization should come before case folding and whitespace handling, because compatibility normalization can turn styled or fullwidth characters into ordinary letters and spaces that the later steps then handle.
import re
import unicodedata
def normalize_for_compare(s: str) -> str:
# Map compatibility variants (styled letters, fullwidth forms, ligatures)
# to their ordinary equivalents.
s = unicodedata.normalize("NFKC", s)
# Drop invisible format characters such as zero-width spaces
# and bidirectional controls (Unicode category Cf).
s = "".join(ch for ch in s if unicodedata.category(ch) != "Cf")
# Case-insensitive matching that handles more than ASCII.
s = s.casefold()
# Collapse runs of whitespace (including tabs and line breaks) to one space.
s = re.sub(r"\s+", " ", s).strip()
return s
def same_ignoring_formatting(a: str, b: str) -> bool:
return normalize_for_compare(a) == normalize_for_compare(b)
In this sketch, casefold() is preferred over lower() because it is designed for caseless matching and handles cases such as the German ß. For strict Unicode-conformant caseless matching, some implementations apply normalization again after case folding; whether that extra pass matters depends on your data.
JavaScript offers the same building blocks: String.prototype.normalize("NFKC") for Unicode normalization and toLowerCase() for simple case handling. If you also want to ignore accents, Intl.Collator or localeCompare with the sensitivity option set to "base" treats strings that differ only in case or accents as equal, using locale-aware rules.
const norm = s => s.normalize("NFKC").toLowerCase().replace(/\s+/g, " ").trim();
norm(a) === norm(b);
// Locale-aware, ignoring case and accents:
a.localeCompare(b, undefined, { sensitivity: "base" }) === 0;
Which approach suits your comparison
Each normalization step removes one kind of difference, and each one can also merge strings you might want to keep distinct. Choose the narrowest set of steps that covers the differences you actually expect.
| Approach | Differences it ignores | What it may wrongly treat as equal | Best for |
| Exact comparison | None | Nothing | Passwords, identifiers, checksums, security-sensitive matching |
| Canonical normalization (NFC or NFD) | Precomposed versus decomposed accents | Nothing visible; only encoding variants that render identically | Default for any user-entered text |
| Compatibility normalization (NFKC) | Styled Unicode letters, fullwidth forms, ligatures, some superscripts | Distinctions such as ² versus 2 or fi versus fi, which may matter in math, chemistry or typography | Search, deduplication, matching text pasted from styled-text tools |
| Case folding | Uppercase versus lowercase | Case-sensitive codes, acronyms or names where case carries meaning | Search and user-facing matching |
| Whitespace collapsing | Extra spaces, tabs, line-ending styles | Content where spacing is meaningful, such as code indentation or fixed-width layouts | Prose, form input, copied text |
| Stripping format characters | Zero-width spaces, bidirectional controls | Emoji sequences and scripts that rely on joiner characters | Cleaning pasted or scraped text |
| Locale-aware collation | Case and accents, according to locale rules | Accented words that are genuinely different in some languages | Sorting and matching names or natural-language text |
Comparison itself is non-destructive and fully reversible as long as you keep the original strings. The risk is in saving normalized output in place of the original: NFKC, case folding and whitespace collapsing all discard information that cannot be recovered.
Illustrative examples
The following are illustrative expectations based on how each step is defined, not recorded output from a specific test run. Verify them in your own environment, especially for mixed scripts.
- "Hello World" versus "hello world": equal after case folding and whitespace collapsing.
- A word written in Mathematical Bold letters versus the same word in ordinary letters: equal after NFKC, because those styled letters have compatibility mappings to plain letters.
- A word containing a zero-width space versus the same word without it: equal only after stripping format characters.
- A word versus its upside-down version made from turned or rotated lookalike letters: generally not equal after NFKC, because many of those lookalikes are separate letters without compatibility mappings. Matching them needs a custom lookup table or a reverse transformation.
- A word versus the same word with its characters reversed: not equal under any normalization. Reverse one string first if you know a reversal was applied.
- Text styled with CSS bold or a CSS mirror effect versus the plain source: equal, because CSS does not change the stored characters. Comparing the rendered appearance, as in a screenshot, would be a different problem.
Comparing whole texts with diff tools
For comparing files or blocks of text rather than single strings, line-based diff tools have built-in options to ignore some formatting. GNU diff documents -i to ignore case, -b to ignore changes in the amount of whitespace, -w to ignore all whitespace, and -B to ignore blank lines. Git's diff command offers similar options, including -w (ignore all whitespace), --ignore-space-change and --ignore-cr-at-eol for line-ending differences.
diff -i -w original.txt edited.txt
git diff -w --ignore-cr-at-eol
These options handle case and whitespace but not Unicode normalization, styled characters or invisible format characters. When those are possible, normalize both files with a script like the one above first, then diff the normalized copies.
Will the comparison hold up where you use it?
Formatting differences often enter through copy and paste. Pasting from a web page, word processor or styled-text generator can bring along non-breaking spaces, smart quotes, invisible characters or substituted Unicode letters. Whether these survive depends on the source and destination applications, so inspect suspicious strings at the code-point level rather than relying on how they look.
- Smart quotes and dashes: curly quotes and en or em dashes are distinct characters from straight quotes and hyphens, and NFKC does not convert them. If they should match, add an explicit replacement step.
- Non-breaking spaces: NFKC maps the common no-break space to an ordinary space, and regular-expression whitespace matching in many languages also covers it, but check your regex engine's definition of whitespace.
- Styled Unicode text and accessibility: because substituted letters are different characters, screen readers may read them letter by letter, announce them by character name or skip them, depending on the software. If text needs to be readable by everyone, use plain characters with CSS styling instead of substituted characters, and test with the assistive technology your audience uses.
- Search and matching in other systems: a database, search index or form validator may apply its own collation or no normalization at all. Do not assume the destination compares strings the way your code does; check its documented collation and normalization settings.
- Security-sensitive comparisons: lookalike characters from different scripts can make two strings appear identical while being different. For usernames, domains or access checks, use exact comparison or a dedicated confusable-detection approach rather than relaxed formatting-insensitive matching.
If you use an online text comparison or normalization tool, the text you paste is sent to that service. Avoid submitting passwords, personal data, contracts or other confidential material unless you know how the service handles and retains input. A local script or a command-line diff keeps the text on your machine.
Choosing your steps
Start with canonical normalization for any human-entered text. Add case folding and whitespace collapsing when spelling and spacing should not matter. Add NFKC and format-character stripping when text may come from styled-text generators or pasted web content. Leave everything out when the exact characters matter, as with credentials and identifiers. Reversed, mirrored or upside-down text needs a matching reverse transformation rather than normalization, and no general-purpose method guarantees a match for every lookalike character, so test with samples of your real input.