Python ascii() Function With Examples


Gaming Laptop Series

The ascii() function of Python returns a string containing a printable representation of an object but escapes the non-ASCII characters in the string. This function is similar to repr() function in Python 2.

In this article, we will understand the usage of Python ascii()function with some examples.

Syntax of Python ascii() function

The syntax of ascii() function in python is –

ascii(object)

Where object can be Python list, set, string, etc.

This function takes a single argument which is a Python object and returns printable equivalent characters for a non-printable character in the object.

Examples of Python ascii() function

The examples of the Python ascii() function are given below –

Example 1:

# Here string contains non-ascii characters
print(ascii(''Welcöme to Pythön progråmming''))
# Following statement will print ascii value of non-ascii symbol
print(ascii('¥'))

When you execute the given program this will display –

output

Now if you try to print these strings with ASCII characters as given below –

print('Welc\xf6me to Pyth\xf6n progr\xe5mming')

print('\xa5')

This will display the original string which contains non-ASCII characters in the output as you can see in the image below-

python print ascii symbol

Example: 2

The following example shows the usage of a list in the ascii() function of Python.

l = ['µ','Hellö', 3]

# passing a list in ascii() function
print(ascii(l))

If you run the above code it will display the given output –

python output

Now if you print the list which includes ASCII characters –

print(['\xb5', 'Hell\xf6', 3])

This will display the list which contains non-ASCII characters in its elements as you can see the output in the image below.

You can also use the tuple, set, etc as an argument to ascii() function.

To know more about ascii() and other standard library functions you can view Python’s official documentation.

Conclusion

So here you have learned the usage of the Python ascii() function. Now if you have a query or feedback then write us in the comments below.

 

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.