ascii()
The built-in ascii()
function returns a string containing a printable representation of an object, with non-ASCII characters escaped 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:
- Generating an ASCII-only representation of strings for logging or debugging purposes
- Escaping non-ASCII characters in data to ensure compatibility with systems that only support ASCII characters
- Preparing data for environments where non-ASCII characters could cause issues
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
In this tutorial, you'll learn how to use Python's rich set of operators and functions for working with strings. You'll cover the basics of creating strings using literals and the str() function, applying string methods, using operators and built-in functions with strings, and more!
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)
- 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)
- Unicode in Python: Working With Character Encodings (Course)