Python Reference · Built-in Functions
Python ascii() function
Reference for Python ascii(): get a printable representation of any object with non-ASCII characters escaped, and how it differs from repr() and str().
The built-in ascii() function returns a string containing a printable representation of an object, like repr(), but with every non-ASCII character replaced by an escape sequence (\xe9, 日, \U0001f600). The result can be safely shown in a terminal, log file or protocol that only handles ASCII.
Only the representation is escaped. The object itself is not changed, and because the output is a string you will see quote characters around text values.
ascii("café") # "'caf\\xe9'"
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input · what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input · what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
ascii(object)
| Name | Description |
|---|---|
object |
Any object. |
Return value: a str. Python calls repr(object) and then escapes every non-ASCII character with \x, \u or \U escapes.
Raises: nothing special; errors raised by the object's __repr__() propagate.
Usage notes
- Escapes are chosen by size. Code points up to
0xFFuse\xNN, up to0xFFFFuse\uNNNN, and larger ones use\UNNNNNNNN. - Same as
!a. In f-strings andstr.format(), the conversion!acallsascii(), just as!rcallsrepr()and!scallsstr(). - Not an encoder.
ascii()returns text, not bytes. To get bytes usestr.encode("ascii", errors="backslashreplace"), which produces similar escapes. - Valid Python source. The escaped text can be evaluated again, so
eval(ascii(x))rebuilds simple values such as strings and lists. - Useful for debugging text. It makes invisible and look-alike characters (non-breaking spaces, accented letters, zero-width characters) visible.
- Quotes remain.
ascii("hi")is"'hi'"(a string that contains quotes). Useprint(ascii(...))to see it without the outer layer. - No effect on ASCII text. Plain ASCII content gives the same result as
repr().