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:

Python
>>> ascii("jalepeño")
"'jalepe\\xf1o'"

ascii() Signature

Python Syntax
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:

Python
>>> ascii("Español")
"'Espa\\xf1ol'"

With a tuple as an argument:

Python
>>> 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:

Python
>>> 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.

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!

basics python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Nov. 21, 2024 • Reviewed by Dan Bader