Python ascii()

Filed Under: Python

Python ascii() function returns the string representation of the object. This function internally calls repr() function and before returning the representation string, escapes the non-ASCII characters using \x, \u or \U escapes.

Python ascii()

Python ascii() is a built-in function and takes a single argument. This argument can be any primitive data type or object. We can also pass list, dict or tuple as an argument. In these cases, the ascii() method will be called on the elements of the collection and string representation is returned.

Python ascii() example with number, boolean, string


s = 5 #numbers
print(ascii(s))

s = True # boolean
print(ascii(s))

# strings
s = 'abc'
print(ascii(s))

s = 'èvõłvé'
print(ascii(s))

Output:


5
True
'abc'
'\xe8v\xf5\u0142v\xe9'

Python ascii() example with list, tuple and dict


l = ['æ', 'b', 'č']
print(ascii(l))

t = (1, 'æ', 'b', 'č', 5)
print(ascii(t))

d = {'â':'å', '2':2, 'ç':'ć'}
print(ascii(d))

Output:


['\xe6', 'b', '\u010d']
(1, '\xe6', 'b', '\u010d', 5)
{'\xe2': '\xe5', '2': 2, '\xe7': '\u0107'}

Python ascii() with custom object

Let’s say we have a class defined as:


class Employee:
    name = ""

    def __init__(self, n):
        self.name = n

Now if we have the following code snippet:


e = Employee('Pànkáj')
print(ascii(e))

Output:


<__main__.Employee object at 0x1061e2d68>

Since we didn’t defined repr() function, Object class repr() definition is used. If we want to use ascii() for any object, we should define its repr() function.

Let’s add below function to Employee class.


   def __repr__(self):
        return self.name

Now the output of above snippet will be:


P\xe0nk\xe1j

That’s all for a quick guide on python ascii() function.

You can checkout complete python script and more Python examples from our GitHub Repository.

Reference: Official Documentation

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages