ThisCalculator

Everyday

Python ascii() Return Value and Usage

Updated · Standard formula, shown below

The calculator for this page is switched off while it is checked. The formula is below, and the worked example in the article shows how to use it by hand.

The Python ascii() function returns a printable representation of an object, escaping any non-ASCII characters as Unicode escape sequences. You pass it any Python object, and it gives you back a string that contains only ASCII characters, making output safe for terminals, logs, and data interchange.

Formula

The ascii() function doesn’t use a mathematical formula. It applies the same logic as repr() for most objects, but with one key difference: any character whose Unicode code point is greater than 127 (i.e., outside the ASCII range) is replaced with its \u or \U escape sequence. The result is always a string containing only characters with code points from 0 to 127.

For a string input, the output is the same as repr() but with non-ASCII characters escaped. For other objects, it calls the object’s __repr__() method and then escapes any non-ASCII characters in the resulting string.

Worked Example

Take the default input "café" (a string with the letter é, which has Unicode code point 233).

  1. Call ascii("café").
  2. ascii() first produces the repr() of the string, which is 'café' (including the quotes).
  3. It then scans the result for any character with code point above 127. The é qualifies.
  4. It replaces é with \u00e9, giving 'caf\u00e9'.
  5. The returned string is 'caf\u00e9' — note that in the actual Python string, the backslash is a real backslash, not an escape for a newline.

So the output displayed in the calculator, 'caf\u00e9', is exactly what ascii("café") returns.

What Does ascii() Actually Return?

The function returns a single string object. That string is a printable representation of the input object, but with all non-ASCII characters converted to escape sequences. The escape sequences are literal text: a backslash followed by ‘u’ and four hex digits (for characters in the Basic Multilingual Plane) or a backslash followed by ‘U’ and eight hex digits (for characters outside that plane).

For example:

  • ascii("hello") returns 'hello' (the quotes are part of the string).
  • ascii("café") returns 'caf\u00e9'.
  • ascii("😀") returns '\U0001f600'.
  • ascii(3.14) returns '3.14'.
  • ascii([1, "é"]) returns [1, '\u00e9'].

Notice that for integers, floats, and other simple types, the output is identical to repr() because those representations already contain only ASCII characters.

How to Use ascii() in Your Code

Using ascii() is straightforward — call it with any object as the argument. The most common use case is to sanitize output for environments that don’t handle Unicode well, such as older terminals, log files, or network protocols that expect ASCII.

  1. Pass the object to ascii(): safe = ascii(my_object).
  2. The result is a string you can print, write to a file, or send over a socket.
  3. If you need the original Unicode back, use eval() or ast.literal_eval() on the string — but be careful with untrusted input.

For example, when logging user-generated content that may contain emoji or accented letters, wrapping the value in ascii() ensures the log stays readable and doesn’t break parsers that assume ASCII.

ascii() vs repr() vs str()

These three functions are often confused, but they serve different purposes:

  • str() returns a human-readable string. For strings, it returns the string itself without quotes. For other objects, it calls __str__().
  • repr() returns a developer-oriented string that, ideally, can be used to recreate the object. For strings, it includes quotes and escapes special characters like newlines.
  • ascii() is identical to repr() except that it also escapes all non-ASCII characters.

In Python 2, ascii() didn’t exist; repr() behaved similarly for byte strings, but Unicode handling was messier. Python 3 introduced ascii() as a clean, explicit way to get an ASCII-only representation.

Common Mistakes and Pitfalls

One frequent mistake is expecting ascii() to convert a string to bytes or to remove non-ASCII characters entirely. It does neither — it escapes them, but the characters are still present in the escape sequence form. If you need to strip non-ASCII characters, use encode('ascii', 'ignore') instead.

Another pitfall is forgetting that the output includes quotes for strings. Beginners often expect ascii("hello") to return hello (without quotes), but it returns 'hello'. This matches repr() behavior and is intentional.

Also, note that ascii() escapes characters based on their Unicode code point, not their byte representation in any specific encoding. So a character like ‘é’ (U+00E9) becomes \u00e9 regardless of whether you’re on a UTF-8 or Latin-1 system.

Limitations and Edge Cases

ascii() works with any object, but the output depends on the object’s __repr__() method. If a custom class’s __repr__() returns a string with non-ASCII characters, ascii() will escape them. If __repr__() returns something that isn’t a string (which is a bug), ascii() will raise a TypeError.

For bytes objects, ascii() returns the same as repr() — a string like b'\x00' — because bytes are already represented with ASCII escapes. For sets and dictionaries, the order of elements in the output may vary between runs, but the escaping behavior is the same.

There’s no performance penalty worth worrying about for typical use. The function is implemented in C and is fast even for large strings.

Frequently Asked Questions

Q: Does ascii() remove non-ASCII characters?
No. It replaces them with escape sequences like \u00e9. The information is preserved, but the output contains only ASCII characters. To actually remove non-ASCII characters, use s.encode('ascii', 'ignore').decode().

Q: What’s the difference between ascii() and repr()?
For most objects, they’re identical. The only difference is that ascii() escapes any character with a Unicode code point above 127, while repr() leaves them as-is (if the terminal supports Unicode).

Q: Can I convert the output back to the original object?
Yes, for strings and literals, you can use ast.literal_eval() on the output of ascii(). For example, ast.literal_eval(ascii("café")) returns the original string. For custom objects, it depends on whether their __repr__() is valid Python code.

Q: Is ascii() the same as encoding to ASCII?
No. encode('ascii') converts a string to bytes and raises an error if a character can’t be encoded. ascii() returns a string with escape sequences, so it never fails on Unicode input.

Q: Why does ascii() add quotes around strings?
Because it’s based on repr(), which is meant to be unambiguous. The quotes make it clear that the result is a string, and they allow the output to be used in code or logs without confusion.

Q: Does ascii() work in Python 2?
No. It was introduced in Python 3. In Python 2, you can use repr() for byte strings, but for Unicode you’d need to manually encode or use a custom function.

Related

Formula used
in t | Input value | - | "café" | 0
out result | ascii() output | - | "'caf\\u00e9'" | 0

Each line is one input (in, sel, list) or one result (out: label, unit, formula, decimals). How the calculators work

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.