ascii()
Like repr(), the built-in ascii() function returns a string containing a printable representation of an object, but it escapes the non-ASCII characters in the string that repr() returns, using \x, \u, or \U escapes. This function is useful for generating an ASCII-only representation of an object:
>>> ascii("jalepeño")
"'jalepe\\xf1o'"
ascii() Signature
ascii(object, /)
Arguments
| Argument | Description |
|---|---|
object |
The object to convert. |
Return Value
- Returns a string representation of the given object with non-ASCII characters escaped.
ascii() Examples
With a string containing non-ASCII characters as an argument:
>>> ascii("Español")
"'Espa\\xf1ol'"
With a tuple as an argument:
>>> ascii((1, 'a', 'á'))
"(1, 'a', '\\xe1')"
ascii() Common Use Cases
The most common use cases for the ascii() function include:
ascii() Real-World Example
Suppose you’re working with a logging system that only supports ASCII characters. You can use ascii() to ensure that all logged messages conform to this restriction:
>>> log_messages = ["Username: español", "Data: El ñandú es un ave exótica"]
>>> ascii_logs = [ascii(message) for message in log_messages]
>>> for log in ascii_logs:
... print(log)
...
'Username: espa\xf1ol'
'Data: El \xf1and\xfa es un ave ex\xf3tica'
By using ascii(), you ensure that all non-ASCII characters are escaped, making the log messages safe for your logging system.
Related Resources
Tutorial
Strings and Character Data in Python
Work with Python strings using a rich set of operators and functions: string literals, the str() function, and the methods you'll use most.
For additional information on related topics, take a look at the following resources:
- When Should You Use .__repr__() vs .__str__() in Python? (Tutorial)
- Unicode & Character Encodings in Python: A Painless Guide (Tutorial)
- Unicode in Python: Working With Character Encodings (Course)
- How to Sort Unicode Strings Alphabetically in Python (Tutorial)
- Strings and Character Data in Python (Course)
- Python Strings and Character Data (Quiz)
- When to Use .__repr__() vs .__str__() in Python (Course)
- Using .__repr__() vs .__str__() in Python (Quiz)
Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.