chr()
Returns the character for the given Unicode code point, e.g. chr(65) is "A". The opposite of ord().
- Returns
- A one-character string.
Example
#print(chr(65), chr(97), chr(233))
print(chr(0x1F40D))
labels = [chr(ord("A") + i) for i in range(4)]
print(labels)Definition and usage
#chr(code) converts an integer into a one-character string whose number in the Unicode standard equals that integer. chr(65) is "A", chr(97) is "a", and chr(233) is "Γ©". The reverse conversion, from a character to a number, is done by ord().
Unicode assigns a number to every character: letters of every alphabet, digits, symbols, and emoji. Valid codes range from 0 to 1,114,111 (hexadecimal 0x10FFFF), and a number outside that range raises a ValueError. Codes are often written in hex, for example chr(0x1F40D) is the snake emoji.
Consecutive letters of the Latin alphabet have consecutive codes, so chr() together with ord() lets you shift letters, like in a Caesar cipher, or generate answer labels A, B, C, D. Accented letters sit outside that run, so calculations like this skip over them.
Syntax
#chr(i)Parameters
#i
int from 0 to 1114111
The character code in the Unicode standard.
More examples
#def caesar(text, shift):
result = ""
for char in text:
if "a" <= char <= "z":
result += chr((ord(char) - ord("a") + shift) % 26 + ord("a"))
else:
result += char
return result
secret = caesar("python is awesome", 3)
print(secret)
print(caesar(secret, -3))print("".join(chr(code) for code in range(ord("a"), ord("f") + 1)))
try:
chr(-1)
except ValueError as error:
print(error)Good practices
#- To check whether a character is a letter or a digit, use the
isalpha()andisdigit()methods instead of comparing codes. They also work with accented letters. - A character with a known code can also be written directly inside a string:
"\u00e9"is"Γ©". - Every lowercase letter of the Latin alphabet is available as the ready-made constant
string.ascii_lowercase, with no need forchr().
Related entries
#- ord()Returns the Unicode code point of a single character, e.g. ord("A") is 65. The opposite of chr().
- str()Converts a value to a string.
- int()Converts a value to an integer.
- str.isdigit()Checks whether a string consists only of digits.
- String slicing [start:stop:step]Getting fragments of a string by index.
Spotted a mistake or missing an example? Write to us.