ascii() ASCII representation
Last updated: 2026-09-22
ascii() ASCII representation
ascii() is similar to repr(), but escapes non-ASCII characters as \x, \u, or \U sequences.
| Category | Built-in Functions |
|---|---|
| Kind | Built-in Function |
| Python Version | all |
📝 Syntax
ascii(object)
⚙️ Parameters
| object Required | Any Python object. |
|---|
Returns:str. The repr() of the object, with non-ASCII characters escaped.
💥 Raises
TypeError— Raised when __repr__ does not return a str (rare).
▶ Example
Edit the code, press Run, and see the result in the output panel:
Output:
'caf\xe9'
'\u4e2d\u6587'
🏷️ Related Built-in Functions
💡 Related Cases
More case studies coming soon — check back later.
❓ FAQ
QWhat is the difference between ascii() and repr()?
Arepr() returns a printable representation of the object and keeps non-ASCII characters; ascii() additionally escapes every non-ASCII character into \x, \u, or \U sequences, guaranteeing pure-ASCII output.
QWhat does ascii('中文') return?
AIt returns '\u4e2d\u6587' (with quotes) — the Chinese characters are escaped into \u sequences rather than kept as-is. To restore them use eval() or json.loads.
QWhat is ascii() useful for?
AIt is useful for log output, confirming a string contains only ASCII characters before cross-system transfer, and debugging invisible or non-printable characters.
QDoes ascii() affect a pure-ASCII string?
ANo. Output for pure-ASCII content matches repr() exactly; escaping only happens when non-ASCII characters are encountered.