Python ascii: How to Use ascii() Function in Python

Python ascii() Example | ascii() Function Tutorial

The ascii() function returns a readable version of any object like Strings, Tuples, Lists, etc. Earlier in Python2, repr() method was used to return a printable representation of the object, but it didn’t escape the non-ASCII characters.

Python ascii()

Python ascii() is an inbuilt method that returns a string containing a printable representation of an object and it escapes the non-ASCII characters in the string using \x, \u or \U escapes. The ascii() function will replace any non-ascii characters with escape characters: å will be replaced with \xe5.

For example, ë is represented as ë by repr()  method, but by ascii() method, it is represented by the Python escape sequence \xeb. Similarly, ö is represented as ö by repr() and \xf6n by ascii()method.



Now, see the following code example.




See the following output.

➜  pyt python3
➜  pyt

So, It returns a string containing the printable representation of an object.

#Python ascii function example with list and tuple

Okay, let’s see the following example of a list and tuple.


tup = ("Ë", "¥", "Ä")

list = ['Facebook', 'FaceBöök']

See the following output.

➜  pyt python3
('\xcb', '\xa5', '\xc4')
['Facebook', 'FaceB\xf6\xf6k']
➜  pyt

#How to get an ASCII value of the character

Python function ord() would get an int value of a char. And if you want to convert back after playing with that number, function chr() does the trick for you.

See the following code example.

print(chr(ord('j') + 3))

See the output.

➜  pyt python3
➜  pyt

Note that ord() function doesn’t give you an ASCII value per se; it gives you a numeric value of that character in whatever encoding it’s in.

Therefore the result of the ord('ä') can be 228 if you’re using Latin-1, or it can raise a TypeError if you’re using the UTF-8.

It can even return a Unicode codepoint instead if you pass it a Unicode.

Finally, Python ascii() Example Tutorial is over.

1 Comment

Leave A Reply

Please enter your comment!
Please enter your name here

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