Menu

Casting

Character and ASCII Conversion

In Python 3 there is no separate character data type. A single character such as "G" is a string of length one: the value is text even though it contains only one character, even when that character looks like a digit.

Each character has an ASCII code, the integer used to represent it. For example, the uppercase letter "G" has the ASCII code 71. Converting between a character and its code is a type conversion (casting), and the direction matters.

FunctionTakesReturnsExample
ord()a characteran integer ASCII codeord("G") gives 71
chr()an integer ASCII codea characterchr(71) gives "G"

ord() takes a one-character string and returns its integer ASCII code, so ord("G") gives 71. It needs exactly one character, so ord("GC") raises an error. chr() takes an integer ASCII code and returns a one-character string, so chr(71) gives "G". Using them the wrong way round, such as ord(71) or chr("G"), raises an error because each function is handed the wrong type of value.

# ord() turns a character into its ASCII code
code = ord("M")
print(code)

# chr() turns an ASCII code back into a character
print(chr(code))

Output:

77
M

Practise this