Isprintable Audit Finds Invisible Characters
str.isprintable flags control, format and non-ASCII space characters, so one comprehension lists suspicious code points in untrusted input before storing.
Code
# Invisible characters disguise themselves as normal text: zero-width spaces slip
# into usernames, no-break spaces replace real ones from copy-pasted input
INVISIBLE = {
"\u200b": "ZERO WIDTH SPACE",
"\u200c": "ZERO WIDTH NON-JOINER",
"\u200d": "ZERO WIDTH JOINER",
"\ufeff": "ZERO WIDTH NO-BREAK SPACE (BOM)",
"\u00a0": "NO-BREAK SPACE",
}
def audit(text: str) -> list[str]:
# isprintable() is False for control, format, and non-ASCII space characters
return [
f"U+{ord(ch):04X} {INVISIBLE.get(ch, 'non-printable')}"
for ch in text
if not ch.isprintable()
]
submissions = {
"[email protected]": "clean input",
"ali\u200b[email protected]": "zero-width in middle",
"pass\u00a0word": "nbsp instead of space",
}
for text, label in submissions.items():
findings = audit(text)
print(f"{label}: {findings if findings else 'clean'}")Output
Captured from a sandboxed run of this snippet in the build pipeline.
clean input: clean
zero-width in middle: ['U+200B ZERO WIDTH SPACE']
nbsp instead of space: ['U+00A0 NO-BREAK SPACE']What the demo audits
The INVISIBLE map names five culprits: zero-width space, non-joiner, joiner, the BOM and the no-break space. audit() lists every character where isprintable() is False, labeling it from the map or falling back to non-printable.
Three submissions run through it: [email protected] prints clean, the zero-width-injected address reports U+200B ZERO WIDTH SPACE, and the NBSP password reports U+00A0 NO-BREAK SPACE, the characters that make two visually identical names unequal.
Points to remember
- isprintable() covers control, format and non-ASCII space categories.
- Run the audit before storing or matching user-supplied text.
Interactive Tools for This Topic
FAQ
- Why do zero-width characters evade visual review?
- They render with no width at all; the audit surfaces them as code points, U+200B in the demo, that a plain visual diff never shows.
Report a problem with this exampleOpens a pre-filled issue on GitHub.