The ascii() built-in function of Python

The ascii() built-in function returns a printable representation of an object. Through __repr__() it often returns an expression that can recreate the object.

Built-in Functions Updated 18 Jan 2017 2 min read

Function signature

ascii(object)

Parameters

object - Any valid Python object

Return value

String - A string representation of the object.

Overview

  • The built-in function ascii() returns a printable string representation of a Python object.
  • The ascii() function calls the __repr__() method of the object passed, which in turn returns the printable representation.
  • If __repr__() is not implemented for a class, Python will give a meaningful string representation comprising of the fully qualified type name and the address of the object.

Example:**<asciitest.Student object at 0x100769898>**

  • As per the Python requirements when the __repr__() method is implemented for a user-defined class the method has to return a string containing an expression with which an object with the same values can be recreated.
  • When the above requirement can't be fulfilled the __repr__() can return<useful description of the object> in the form a string. It is better to make this string as rich as possible in terms of the information it conveys to the developer so as to aid in the debugging process.
  • The built-in function ascii() prints any non-ascii values by prefixing them with one of the suitable escape characters \x, \u and \U.

Example

While defining the trivial complex number class Complex, say the developer for some reason wants to represent the "i" prefix of the imaginary part with the string img.This can be done through the __repr__() implementation of the trivial Complex class. The example prints the string representation of the trivial Complex instance twice. Once without using the built-in ascii() function and once using the ascii() function. The output is the same in both the cases. The reason is the built-in funtction ascii() in turn calls the __repr__() method of the trivial Complex class.

Output
# Example Python program that defines a trvial complex number

            # class and uses the built-in function ascii() to print

            # the ascii string representation of the trvial complex number

            # instance

# A trivial defintion of complex number

            class complex:

                def __init__(self, realPart, imgPart):

                    self.x  = realPart

                    self.y  = imgPart

    def __repr__(self):

                    strForm = "%2.2fimg%2.2f"%(self.x, self.y)

                    return strForm

# Create a complex number using the new definition

            c1 = complex(10, -1)

            print(c1)

# Try calling ascii() explicitly

            asciiStr = ascii(c1)

            print(asciiStr)

Output

Output
10.00img-1.00

10.00img-1.00