ascii() in Python
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.
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.
In this example, str contains not-ASCII character and our task is to display its ASCII value from the given string.
'G \xeb \xea k s f ? r G ? e k s'
Here we take variable with multiline string and pass it into the ascii() and it returns “\n”, the value of new line is “\n”.
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.
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 firstname.lastname@example.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.