What is Python ascii function?

The ascii() function:

  • Takes an argument (object) that can be a string, list, tuple etc.
  • It returns a string that contains a printable representation of that object.
  • The ascii function escapes any non-ASCII characters in the returned string
  • The non-ASCII characters are replaced by escape characters i.e. \x, \u and \U

Syntax of using ascii function

The syntax of using the ascii function is simple:

Str = ascii(object)

An example of using string object in ascii function

In this example, normal text is used in the ascii function. After this example, I will show you using non-ASCII characters:

The code and output:

#A demo of ascii function

an_str = 'simple text'


The result:

‘simple text’

Using non-ascii characters in a string

Now see the output as I used the non-ASCII character in a string object and used in the ascii() function. First, I used the copyright sign and this is followed by using the registered sign:

str_non = 'copyright = ©'


The output:

‘copyright = \xa9’


str_non = 'Registered sign = ®'


The output:

‘Registered sign = \xae’

So, How ascii function works?

Basically, the ascii() function works by encoding the output of repr() function to use escape sequences for any codepoint in the output produced by repr() function that is not within the ASCII range.

In Python 2, the repr() function would have produced ‘\xae’ for ‘®’ sign. However, in Python 3, the repr() will result in the actual value as the output. For example:

In Python 2:

print repr("®")

The result:


In Python 3:


The output:


However, as we have seen in the above example, the ascii() produced the following:


The output:


Now, let us look at another example of using the ascii() function.

An example of using a list object in ascii function

A list with a few elements is created. The string elements also include Latin-1 characters (non-ASCII) along with normal characters. See the code and its result:

#A demo of ascii with a list

a_List = ['©', 'á', 'µ' ,'bé' ,'pound' ,'£']


The result:

[‘\xa9’, ‘\xe1’, ‘\xb5’, ‘b\xe9’, ‘pound’, ‘\xa3’]


Author - Atiq Zia

Atiq is the writer at jquery-az.com, an online tutorial website started in 2014. With a passion for coding and solutions, I navigate through various languages and frameworks. Follow along as we solve the mysteries of coding together!