The Python chr function serves to retrieve a string that corresponds to a character based on a given Unicode code integer. For instance, calling chr(97) will yield the string 'a'. This function requires an integer input and raises an error if the value surpasses the defined limits. The typical range for the argument is from 0 to 1,114,111.
Python chr Function Syntax
It has the following syntax:
chr(i)
Parameters
- i : It is an integer value.
Return
This function provides a string representation of a given character.
Different Examples for Python chr Function
Let us examine several instances of the chr function to grasp its capabilities effectively.
Python chr Function Example 1
Here is a straightforward illustration of utilizing the chr function, which yields the character corresponding to a given integer value. The output type of this function is a string, and this can be confirmed as well.
# Python chr() function example
# Calling function
result = chr(102) # It returns string representation of a char
result2 = chr(112)
# Displaying result
print(result)
print(result2)
# Verify, is it string type?
print("is it string type:", type(result) is str)
Output:
f
p
is it string type: True
Python chr Function Example 2
The chr function accepts an integer that falls within a specified range. An error will be raised if the provided value surpasses this range. Refer to the example below.
# Python chr() function example
# Calling function
result = chr(11) # It returns string representation of a char
result2 = chr(11111111) # If value is out of range
# Displaying result
print(result)
print(result2)
Output:
ValueError: chr() arg not in range(0x110000)
Python chr Function Example 3
In this instance, we are utilizing a collection of integers with the chr function, which converts each integer into its corresponding character value as defined by the Unicode standard. Below is an illustrative example.
# Python chr() function example
data = [112,97,114,119,115,10.5]
result = chr(11) # It returns string representation of a char
# Calling function
for d in data:
print("Char at",d,"is:",chr(d))
Output:
TypeError: integer argument expected, got float
Char at 112 is: p
Char at 97 is: a
Char at 114 is: r
Char at 119 is: w
Char at 115 is: s