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.
On this page

Example

#
Python
print(chr(65), chr(97), chr(233))
print(chr(0x1F40D))

labels = [chr(ord("A") + i) for i in range(4)]
print(labels)
Resultsaved result, you can check it
A a Γ©
🐍
['A', 'B', 'C', 'D']

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

#
Syntax
chr(i)

Parameters

#
  • i

    int from 0 to 1114111

    The character code in the Unicode standard.

More examples

#
Caesar cipher
Python
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))
Resultsaved result, you can check it
sbwkrq lv dzhvrph
python is awesome
A range of characters and an invalid code
Python
print("".join(chr(code) for code in range(ord("a"), ord("f") + 1)))

try:
    chr(-1)
except ValueError as error:
    print(error)
Resultsaved result, you can check it
abcdef
chr() arg not in range(0x110000)

Good practices

#
  • To check whether a character is a letter or a digit, use the isalpha() and isdigit() 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 for chr().

Related entries

#

Spotted a mistake or missing an example? Write to us.