Python ascii() Function



The Python ascii() function is a built-in function that returns a readable version of the specified object. Here, the object could be Strings, Tuples, Lists, etc. If this function encounters a non-ASCII character, it will replace it with an escape character, such as \x, \u and \U.

This function is useful in the case when we need to ensure that the end result complies with the ASCII standard, which is a character encoding standard that stands for American Standard Code for Information Interchange.

Syntax

Following is the syntax of the Python ascii() function −

ascii(object)

Parameters

The Python ascii() function accepts a single parameter −

  • object − It represents an object such as a list, string, or tuples.

Return Value

The Python ascii() function returns a String containing printable representation of an object.

Examples

Let's understand how ascii() function works with the help of some examples −

Example 1

The following example shows how to use the Python ascii() function. Here we are defining a string and applying the ascii() function to convert it into a String with ASCII characters. The result will be the same as original string as it already has ASCII characters.

orgnl_str = "Learn Python Methods"
new_ascii_str = ascii(orgnl_str)
print("The new ascii representation of given string:", new_ascii_str)  

When we run the above program, it produces following result −

The new ascii representation of given string: 'Learn Python Methods'

Example 2

In the following example, we are defining a string with some non-ASCII characters and applying the ascii() function to convert it into a String with ASCII characters.

orgnl_str = "Learn Pythön Methods"
new_ascii_str = ascii(orgnl_str)
print("The new ascii representation of given string:", new_ascii_str)  

When we run the above program, it produces following result −

The new ascii representation of given string: 'Learn Pyth\xf6n Methods'

Example 3

The code below shows how to use ascii() function to convert a list with non-ASCII characters into a list with ASCII characters.

orgnl_lst = [71, 87, "é", "→",5]
new_ascii_lst = ascii(orgnl_lst)
print("The new ascii representation of given list:", new_ascii_lst) 

Output of the above code is as follows −

The new ascii representation of given list: [71, 87, '\xe9', '\u2192', 5]

Example 4

In the code below a set named 'orgnl_set' is created. Then all the elements present in the set are replaced using the ascii() function. Here, we retrieve the set with ASCII characters.

orgnl_set = {"©", "¥", "é", "→"}
new_ascii_set = ascii(orgnl_set)
print("The new ascii representation of given set:", new_ascii_set)  

Following is an output of the above code −

The new ascii representation of given set: {'\xa5', '\xa9', '\xe9', '\u2192'}
python_built_in_functions.htm
Advertisements