ascii() Function in Python

Python ascii() Function

The ascii() function in Python is a built-in function that returns a string containing a printable representation of an object. It is particularly useful when dealing with non-ASCII characters or when you need to represent special characters in a readable format.

Here is the syntax for the ascii() function:

ascii(object)

The object parameter is the object you want to represent as a string. It can be a string, a number, a list, a dictionary, or any other Python object.

The ascii() function works by returning a string that represents the object using the ASCII character set. It replaces non-ASCII characters with escape sequences that start with the backslash character ().

Example:

Let's say we have a string that contains non-ASCII characters:

text = "Café"

If we print the string directly, we might encounter encoding issues depending on the environment or the output device. However, if we use the ascii() function, it will convert the non-ASCII character "é" to its ASCII representation:

print(ascii(text)) // Output : 'Caf\xe9'

In this case, the character "é" is represented as \xe9 in the ASCII format.

It's important to note that the ascii() function is different from the repr() function. While both functions return a string representation of an object, the repr() function aims to create a string that can be used to recreate the object, while the ascii() function focuses on representing the object using ASCII characters.