Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

ascii() in Python

  • Difficulty Level : Hard
  • Last Updated : 13 Sep, 2021

Python ascii() function returns a string containing a printable representation of an object and escapes the non-ASCII characters in the string using \x, \u or \U escapes

Syntax: ascii(object)

The method can take only one parameter, an object that can be a list, strings, etc. As already discussed, it returns a printable representation of an object.  

Python ascii() function Examples 

Input : ascii("¥")
Output : '\xa5'

Input : ascii("µ")
Output : '\xb5'

Input : ascii("Ë")
Output : '\xcb'

We see that in these examples, all the non-ASCII characters have been escaped, i.e, their encoded code gets displayed by using the ascii() method.

Example 1:

In this example, str contains not-ASCII character and our task is to display its ASCII value from the given string.

Python3




# Python program to illustrate ascii()
str = "G ë ê k s f ? r G ? e k s"
print (ascii(str))

Output: 

'G \xeb \xea k s f ? r G ? e k s'

Example 2:

Here we take variable with multiline string and pass it into the ascii() and it returns “\n”, the value of new line is “\n”.

Python3




str = '''Geeks
for
geeks'''
print(ascii(str))

Output:

'Geeks\nfor\ngeeks'

ascii() vs print():

Here we will see the difference between ascii() function and the print() function. For this, we have taken variables with multiline string and try to display them with both functions. After code execution, you will get different output, because ascii() function escapes the non-ASCII character while the print function print does not escape this value.

Python3




str = '''Geeks
for
geeks'''
print("Display with ascii function : ",ascii(str))
print("Display with print function : ",str)

Output:

Display with ascii function :  'Geeks\nfor\ngeeks'
Display with print function :  Geeks
for
geeks

This article is contributed by Chinmoy Lenka. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!