Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
chr () in Python
The chr() function in Python returns a string representing a character whose Unicode code point is the integer supplied as parameter. For example, chr(65) returns the string 'A', while chr(126) returns the string '~'.
Syntax
The syntax of the chr() function is as follows ?
chr(n)
Where n is an integer value representing the Unicode code point.
Basic Example
The below program shows how chr() is used. We supply various integer values as parameters and get back the respective characters ?
# Printing the strings from chr() function print(chr(84), chr(85), chr(84), chr(79), chr(82))
T U T O R
Using a Series of Numbers
We can use Python data structures like lists to loop through a series of numbers and apply the chr() function to create a required string ?
result_str = ""
series = [84, 85, 84, 79, 82, 73, 65, 76, 83]
for code in series:
char = chr(code)
result_str = result_str + char
print(result_str)
TUTORIALS
More Examples
Here are additional examples showing different Unicode ranges ?
# ASCII lowercase letters print(chr(97), chr(98), chr(99)) # a b c # ASCII digits print(chr(48), chr(49), chr(50)) # 0 1 2 # Special characters print(chr(64), chr(35), chr(36)) # @ # $ # Creating a string from a range numbers = list(range(65, 70)) # [65, 66, 67, 68, 69] letters = ''.join(chr(num) for num in numbers) print(letters)
a b c 0 1 2 @ # $ ABCDE
Key Points
- chr() accepts integers from 0 to 1,114,111 (0x10FFFF)
- It's the inverse of the ord() function
- Commonly used for ASCII values (0-127) and Unicode characters
- Raises ValueError if the argument is outside the valid range
Conclusion
The chr() function converts Unicode code points to their corresponding characters. It's useful for generating characters programmatically and working with character encodings in Python applications.
