Python chr() Function
chr()is a built-in function in Python used to convert an integer to the corresponding character.
chr()It accepts a Unicode code point (integer) and returns the corresponding character. It isord()the inverse function of.
Word Definition: chrYescharacterabbreviation of (character).
Basic Syntax and Parameters
Syntax Format
chr(i)
Parameter Description
- Parameter i:
- Type: Integer (Unicode code point, 0 to 1,114,111)
- Description: The Unicode code point to be converted to a character.
Function Description
- Return Value: Returns a string of length 1, i.e., the corresponding character.
- Range: The valid Unicode code point range is 0 to 1,114,111 (0x10FFFF).
Examples
Example 1: Basic Usage
Example
# Basic English characters
print(chr(65)) # Output: A
print(chr(90)) # Output: Z
print(chr(97)) # Output: a
print(chr(122)) # Output: z
# Digit characters
print(chr(48)) # Output: 0
print(chr(57)) # Output: 9
# Common symbols
print(chr(33)) # Output: !
print(chr(64)) # Output: @
print(chr(32)) # Output: space
# Chinese
print(chr(20013)) # Output: middle
print(chr(25991)) # Output: language
print(chr(65)) # Output: A
print(chr(90)) # Output: Z
print(chr(97)) # Output: a
print(chr(122)) # Output: z
# Digit characters
print(chr(48)) # Output: 0
print(chr(57)) # Output: 9
# Common symbols
print(chr(33)) # Output: !
print(chr(64)) # Output: @
print(chr(32)) # Output: space
# Chinese
print(chr(20013)) # Output: middle
print(chr(25991)) # Output: language
Expected output:
A Z a z 0 9 ! @ 中 文
Code explanation:
- 65-90 are the Unicode code points for uppercase letters A-Z.
- 97-122 are the Unicode code points for lowercase letters a-z.
- 48-57 are the Unicode code points for digits 0-9.
Example 2: Using with ord()
Example
# ord() is the inverse function of chr()
print(ord('A')) # Output: 65
print(chr(65)) # Output: A
print(chr(ord('A') + 1)) # Output: B
# Iterate over uppercase letters
for i in range(65, 91):
print(chr(i), end=" ")
print() # Output: A B C ... Z
# Generate character art
pattern = []
for i in range(0, 256, 16):
row = ''.join(chr(j) for j in range(i, min(i+16, 256)))
pattern.append(row)
print(pattern[0]) # Output: !"#$%&'()*+,-./
print(ord('A')) # Output: 65
print(chr(65)) # Output: A
print(chr(ord('A') + 1)) # Output: B
# Iterate over uppercase letters
for i in range(65, 91):
print(chr(i), end=" ")
print() # Output: A B C ... Z
# Generate character art
pattern = []
for i in range(0, 256, 16):
row = ''.join(chr(j) for j in range(i, min(i+16, 256)))
pattern.append(row)
print(pattern[0]) # Output: !"#$%&'()*+,-./
Expected output:
65 A B A B C D E F G H I J K L M N O P Q R S T U V W X Y Z !"#$%&'()*+,-./
chr()andord()are inverse functions of each other, often used together to handle character encoding.
Other Extensions
Python3 Built-in Functions