Python chr() Function



The Python chr() function is used to retrieve the string representation of a specific Unicode value.

In simpler terms, if you have a number representing the Unicode code point of a character, using the chr() function with that number will give you the actual character. For example, calling "chr(65)" results in 'A' since 65 represents the Unicode code point for the uppercase letter 'A'. This function operates as the inverse of the "ord()" function, which provides the code point for a given character.

The chr() function accepts Unicode values within the range of 0 to 1114111. If a value outside this range is provided, the function raises a ValueError.

Syntax

Following is the syntax of python chr() function −

chr(num)

Parameters

This function accepts an integer value as a parameter.

Return Value

This function returns a string representing the character with the given ASCII code.

Example

Following is an example of the python chr() function. Here, we are retrieving the string corresponding to the Unicode value of "83" −

unicode_value = 83
string = chr(unicode_value)
print("The string representing the Unicode value 83 is:", string)

Output

Following is the output of the above code −

The string representing the Unicode value 83 is: S

Example

Here, we are retrieving the string values of an array of Unicode value using the chr() function −

unicode_array = [218, 111, 208]
for unicode in unicode_array:
   string_value = chr(unicode)
   print(f"The string representing the Unicode value {unicode} is:", string_value)

Output

The output obtained is as follows −

The string representing the Unicode value 218 is: Ú
The string representing the Unicode value 111 is: o
The string representing the Unicode value 208 is: Ð

Example

In this example, we are concatenating the string values of the Unicode values "97" and "100" −

unicode_one = 97
unicode_two = 100
string_one = chr(unicode_one)
string_two = chr(unicode_two)
concatenated_string = string_one + string_two
print("The concatenated string from the Unicode values is:", concatenated_string)

Output

The result produced is as follows −

The concatenated string from the Unicode values is: ad

Example

If a Unicode value that exceeds the range, i.e., is greater than the length of a string of 1 character, is passed to the chr() function, a ValueError will be raised.

Here, we are passing "-999" to the chr() function to demonstrate the value error −

unicode_value = -999
string_value = chr(unicode_value)
print("The string representation for Unicode values -999 is:", string_value)

Output

We can see in the output that we get a ValueError because we have passed a Unicode value that is invalid with length greater than 1 −

Traceback (most recent call last):
  File "C:\Users\Lenovo\Desktop\untitled.py", line 2, in <module>
    string_value = chr(unicode_value)
ValueError: chr() arg not in range(0x110000)
python-chr-function.htm
Advertisements