ascii()
The ASCII-safe cousin of repr() — same format, but non-ASCII becomes escape sequences.
Demo
ascii() is repr() with a filter: every character with codepoint >= 128 becomes an escape sequence (\xHH, \uXXXX, or \UXXXXXXXX). This produces output that is safe for ASCII-only sinks — old log formats, some file systems, protocols that mangle non-ASCII. In modern UTF-8 environments repr() is usually more readable.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| object | Any | yes | Any value. Python calls repr() on it, then escapes every non-ASCII codepoint. |
Return value
str — A string like repr(object), but every character outside the ASCII range (codepoint >= 128) is replaced with an escape sequence: \xHH for U+0080..U+00FF, \uXXXX for U+0100..U+FFFF, \U00XXXXXX for U+10000+.
Common patterns
log.error("bad name: %s", ascii(name))
s = ascii("café") # "'caf\xe9'" eval(s) # "café"
print(ascii(mystery_string)) # reveals BOM, zero-width joiners, etc.
Examples
Pitfalls
repr("café") == ascii("café")
repr shows Unicode as Unicode; ascii escapes it
ascii("😀")
repr("😀")
"café".encode("ascii", errors="backslashreplace")
ascii("café")
When to use
- ASCII-only log destinations (older syslog, protocols with limited charsets)
- Diagnostic output where non-ASCII characters would mangle
- Detecting invisible zero-width or BOM characters
- Environments where the terminal cannot render UTF-8
- Modern UTF-8 environment → repr() is more readable
- JSON serialization → json.dumps has its own ensure_ascii option
- Displaying user-facing text → str() and print()
- Debug output that a human will read → repr() shows Unicode as Unicode
Notes
FAQ
Both quote strings and escape control chars. repr keeps non-ASCII characters as-is (utf-8 safe). ascii escapes non-ASCII into \x, \u, or \U sequences. Use repr in UTF-8 environments; ascii when the sink cannot handle non-ASCII.