chr() function in Python

Programming PYTHON BUILT-IN FUNCTIONS SERIES Image

    Introduction

    The chr() function converts an integer to its unicode character and returns it.

    The syntax of chr() function is:

    chr(num)

    The chr() function takes in a single parameter num which is an integer in the range 0 to 1,114,111. It can return the following:

    • unicode character of the corresponding integer if the integer value is in the range
    • ValueError, in the case integer value is out of range
    • TypeError, in the case a non-integer argument is passed

    You can see the unicode representation of different characters here.

    Example 1

    Let us pass integer arguments in the correct range.

    num1 = 65
    print(chr(num1))
    
    num2 = 120
    print(chr(num2))
    

    Output

    A
    x

    In the above example, we have passed integers to the chr() function, and it returns the corresponding unicode characters.
     

    Example 2

    Let us again pass integer arguments but this time, the values will be out of range.

    num = -65
    print(chr(num))

    Output

    ValueError: chr() arg not in range(0x110000)

    In the above example, we passed -65 as the argument, which is out of range, and hence it throws the ValueError.
     

    Example 3

    Let us now pass something other than integer as the argument to the chr() function.

    print(chr('Hello'))

    Output

    TypeError: an integer is required (got type str)

    As the error itself tells, an integer is required but we have passed string.
     

    Conclusion

    In this part, we learned about the Python chr() function with the help of examples.

    If you liked this post, you can consider subscribing to my newsletter.


    If you read this far, support the author to show them you care.

    0 Comments

    To add a comment, please Signup or Login

    OR