chr
Think of letters like A, B and C. These are parts of words. But they have an underlying representation. A sequence of bits that represents that letter.
In Python characters are represented by numbers. Often we use a one-character string
. With ord
we convert this into an integer. With chr
, an integer into a string
.
In this program, each "letter" is a one-character string
. We call ord
and the result in an integer. We can do things like multiply or add that integer.
letters = "ABCabc123" for letter in letters: # Get number that represents letter in ASCII. number = ord(letter) print(letter, "=", number)A = 65 B = 66 C = 67 a = 97 b = 98 c = 99 1 = 49 2 = 50 3 = 51
Next we consider the chr
built-in function. This does the opposite of ord
. It converts a number (an integer) into a one-character string
.
numbers = [97, 98, 99] for number in numbers: # Convert ASCII-based number to character. letter = chr(number) print(number, "=", letter)97 = a 98 = b 99 = c
Let's do something really crazy. Here we create strings with chr
in for
-loops for use as the mapped keys and values of maketrans
. We then translate the strings.
# Generate string for translation. initial = "" for i in range(97, 97 + 26): initial += chr(i) # Generate mapped chars for string. translated = "" for i in range(97, 97 + 26): translated += chr(i - 10) print("INITIAL ", initial) print("TRANSLATED", translated) # Create a lookup table. table = str.maketrans(initial, translated) # Translate this string. value = "thank you for visiting" result = value.translate(table) print("BEFORE", value) print("AFTER ", result)INITIAL abcdefghijklmnopqrstuvwxyz TRANSLATED WXYZ[\]^_`abcdefghijklmnop BEFORE thank you for visiting AFTER j^Wda oek \eh l_i_j_d]
The simplest examples above would not be found in real programs. But algorithms like ROT13, which are used sometimes in programs, also can be implemented with ord
and chr
.
chr
built-ins help transform characters and strings. But they are not ideal for all translations.maketrans
and translate()
we can translate strings. We can use chr
and ord
to build translation strings for these methods.Chr and ord
are something we need to know to effectively use Python. There is a difference between an integer and a one-character string
.
We must convert to an integer with ord
—and back to a string
with chr
. We can change characters by adding or subtracting offset values.