AppDividend
Latest Code Tutorials

Python chr() Example | chr() Function Tutorial In Python

0

Python chr() Example | chr() Function Tutorial In Python is today’s topic. The chr() method returns the character (a string) from the integer which represents Unicode code point of the character. So, the chr() method returns a string representing a character whose Unicode code point is an integer. Python chr() function takes an integer as an argument and returns a string representing a character at that code point.

Python chr() Example

The syntax of chr() is following.

chr(i)

If the integer i is outside the range, ValueError will be raised.

The chr() function takes only one integer as a parameter.

The range may vary from 0 to 1,1141,111(0x10FFFF in base 16).

The chr() method returns the character whose Unicode point is num, an integer.

See the following code example.

numbers = [99, 38, 98]

for number in numbers:

    print("Character of ASCII value", number, "is ", chr(number))

See the following output.

➜  pyt python3 app.py
Character of ASCII value 99 is  c
Character of ASCII value 38 is  &
Character of ASCII value 98 is  b
➜  pyt

Okay, now let’s give some input which is out of the range.

data = -1
print(chr(data))

See the following output.

➜  pyt python3 app.py
Traceback (most recent call last):
  File "app.py", line 2, in <module>
    print(chr(data))
ValueError: chr() arg not in range(0x110000)
➜  pyt

The chr() function returns the character that represents the specified Unicode.

Sometimes we need to convert an ASCII character to its corresponding character and for such cases Python chr() function is used.

#Python ord() Function

Python ord() and chr() functions are exactly opposite of each other.

Python ord() function takes string argument of a single Unicode character and return its integer Unicode code point value.

See the following code.

# app.py

print(ord('Ǵ'))
print(ord('ɘ'))
print(ord('ʼ'))

See the following output.

➜  pyt python3 app.py
500
600
700
➜  pyt

That means, it will give us the integer value, which is opposite returning the Unicode character value.

Finally, The chr() Function Tutorial In Python is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.