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'

print(ascii(an_str))

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 = ©'

print(ascii(str_non))

The output:

‘copyright = \xa9’

Similarly,

str_non = 'Registered sign = ®'

print(ascii(str_non))

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:

 ‘\xae’

In Python 3:

print(repr("®"))

The output:

‘®’

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

print(ascii("®"))

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:

#A demo of ascii with a list



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

print(ascii(a_List))

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 unravel the mysteries of coding together!