chr () in Python

Python Methods and Functions

The chr () method returns a string representing a character whose Unicode code point is an integer. 
Syntax :

  chr (num)   num:  integer value 
  • The chr () method accepts only one integer as an argument.
  • The range can range from 0 to 1,1141,111 (0x10FFFF in base 16).
  • The chr ( ) returns a character whose unicode point is num, an integer.
  • If an out-of-range integer is passed, the method returns a ValueError.

Example. Suppose we want to print "G eeksfor G eek s".

# Python program for illustration
# chr () built-in function

  

print ( chr ( 71 ), chr ( 101 ),

chr ( 101 ), chr ( 107 ),

chr ( 115 < code class = "plain">), chr ( 32 ),

chr ( 102 ), chr ( 111 ),

chr ( 114 ), chr ( 32 ),

chr ( 71 ), chr ( 101 ) ,

chr ( 101 < code class = "plain">), chr ( 107 ), 

chr ( 115 ))

Output:

 G eeksfor G eeks 

Another example:

# Python program for illustration
# chr () built-in function

 

numbers = [ 17 , 38 , 79 ]

 

< code class = "keyword"> for number in numbers:

 

# Convert an ASCII number to a character.

letter = chr (number)

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

Output:

 Character of ASCII value 17 is Character of ASCII value 38 is & amp; Character of ASCII value 79 is O 

What happens if we give something out of range?

# Python program for illustration
# chr () inline function
# if given value
# out of range

 
# Convert ASCII number to character

print ( chr ( 400 ))

Output:

 No Output 

We will not get any output, and the compiler will throw an error:

 Traceback (most recent call last): File "/ home / 484c76fb455a62 4cc137946a244a9aa5.py ", line 1, in print (chr (400)) UnicodeEncodeError:' ascii' codec can't encode character 'u0190' in position 0: ordinal not in range (128) 




Tutorials