Integer-only Functions
In addition to the built-in functions for all numeric types, Python supports a few that are specific only to integers (plain and long). These functions fall into two categories, base presentation with hex() and oct(), and ASCII conversion featuring chr() and ord().
Base Representation
As we have seen before, Python integers automatically support octal and hexadecimal representations in addition to the decimal standard. Also, Python has two built-in functions which return string representations of an integer’s octal or hexadecimal equivalent. These are the oct() and hex() built-in functions, respectively. They both take an integer (in any representation) object and return a string with the corresponding value. The following are some examples of their usage:
>>> hex(255) '0xff' >>> hex(230948231) '0xdc3fd87' >>> hex(65536*2) '0x20000' >>> oct(255) '0377' >>> oct(230948231) '01560776607' >>> oct(65535*2) '0377776'
ASCII Conversion
Python also provides functions to go back and forth between ASCII (American Standard Code for Information Interchange) characters and their ordinal integer values. Each character is mapped to a unique number in a table numbered from 0 to 255. This number does not change for all computers using the ASCII table, providing consistency and expected program behavior across different systems. chr() takes a single-byte integer value and returns a one-character string with the equivalent ASCII character. ord() does the opposite, taking a single ASCII character in the form of a string of length one and returns the corresponding ASCII value as an integer:
>>> ord('a') 97 >>> ord('A') 65 >>> ord('O') 79 >>> chr(97) 'a' >>> chr(65L) 'A' >>> chr(48) '0'