Hit enter after type your search item

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:


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:


The output:

‘copyright = \xa9’

Similarly,


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:


The result:

 ‘\xae’

In Python 3:


The output:

‘®’

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


The output:

‘\xae’

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:


The result:

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

 

This div height required for enabling the sticky sidebar