2

Python chr(): A Step-By-Step Guide

 3 years ago
source link: https://dev.to/itsmycode/python-chr-a-step-by-step-guide-3dj2
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Python chr(): A Step-By-Step Guide

Sep 19 Originally published at itsmycode.com on Sep 18

・2 min read

ItsMyCode |

The chr() function takes an integer (representing Unicode) as an input argument and returns a string representing a character.

Syntax – chr(num)

Parameter and Return Value

  • The chr() function can only take one parameter and integer as an argument.
  • The valid range of the integer is between 0 to 1,1141,111(0x10FFFF in base 16), representing the equivalent Unicode characters.
  • If you pass an integer outside the range, Python will throw ValueError
  • The chr() method returns a string(single character) whose Unicode code point is an integer.
  • The chr() is nothing but the inverse of ord() function.

Example of chr() function in Python

In the below examples, we are passing various Unicode numbers to chr() method and converting them into equivalent Unicode characters.

print("Unicode character of integer 65 is", chr(65))
print("Unicode character of integer 8364 is", chr(8364))

# Print Alphabets using Unicode
for i in range(65, 65+26):
    print(chr(i), end = " , ")
Enter fullscreen modeExit fullscreen mode

Output

Unicode character of integer 65 is A
Unicode character of integer 8364 is €
A , B , C , D , E , F , G , H , I , J , K , L , M , N , O , P , Q , R , S , T , U , V , W , X , Y , Z ,
Enter fullscreen modeExit fullscreen mode

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

If you pass an integer outside the Unicode range, Python will throw a ValueError , as shown in the below example.

print(chr(4000000))
print(chr(-4))
Enter fullscreen modeExit fullscreen mode

Output

Traceback (most recent call last):
  File "c:\Projects\Tryouts\main.py", line 1, in <module>
    print(chr(4000000))
ValueError: chr() arg not in range(0x110000)
Enter fullscreen modeExit fullscreen mode

The post Python chr(): A Step-By-Step Guide appeared first on ItsMyCode.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK