AppDividend
Latest Code Tutorials

Python ascii() Example | ascii() Function Tutorial

0

Python ascii() Example | ascii() Function Tutorial is today’s topic. Python ascii() 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 returns a readable version of any object like Strings, Tuples, Lists, etc. The ascii() function will replace any non-ascii characters with escape characters: å will be replaced with \xe5.

Python ascii() Example

Earlier in Python2, repr() method was used to return a printable representation of the object, but it didn’t escape the non-ASCII characters.

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.

The syntax of the ascii() function is following.

ascii(object)

Now, see the following code example.

print(ascii("¥"))

print(ascii("µ"))

print(ascii("Ë"))

See the following output.

➜  pyt python3 app.py
'\xa5'
'\xb5'
'\xcb'
➜  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 list and tuple.

# app.py

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

list = ['Facebook', 'FaceBöök']
print(ascii(list))

See the following output.

➜  pyt python3 app.py
('\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(ord('k'))
print(chr(97))
print(chr(ord('j') + 3))

See the output.

➜  pyt python3 app.py
107
a
m
➜  pyt

Note that ord() function doesn’t give you a 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 | ascii() Function Tutorial is over.

Leave A Reply

Your email address will not be published.

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