Python unichr() Function



In Python 2, unichr() function was used to convert a Unicode code point to its corresponding Unicode character. It is similar to the "chr()" function in Python 3.

In Python 2, characters were represented as Unicode using the "unicode" type by default. The unichr() function was used to create Unicode characters from their respective code points. For example, calling "unichr(65)" would produce the Unicode character 'A', as 65 corresponds to the Unicode code point for the uppercase letter 'A'.

The unichr() function from Python 2 has been deprecated in Python 3. Instead, the built-in chr() function is now used universally for both ASCII and Unicode characters in Python 3.

Syntax

Following is the syntax of python unichr() function −

unichr(num)

Parameters

This function accepts an integer value as a parameter.

Return Value

This function returns a Unicode string containing the character represented by that code point.

Example 1

Following is an example of the python unichr() function. Here, we are creating a Unicode character from the Unicode code point "65" −

Open Compiler
unicode_value = 65 string = unichr(unicode_value) print("The string representing the Unicode value 65 is:", string)

Output

Following is the output of the above code −

('The string representing the Unicode value 65 is:', u'A')

Example 2

Here, we are using the unichr() function within a loop to generate Unicode characters for code points ranging from "65" to "69" −

Open Compiler
for i in range(65, 70): unicode_char = unichr(i) print "The unicode string obtained is:", unicode_char

Output

The output obtained is as follows −

The unicode string obtained is: A
The unicode string obtained is: B
The unicode string obtained is: C
The unicode string obtained is: D
The unicode string obtained is: E

Example 3

In this example, we are using the unichr() function to create a Unicode character for the code point "9786", which corresponds to a smiley face −

Open Compiler
smiley_face = unichr(9786) print smiley_face.encode('utf-8')

Output

The result produced is as follows −

😊

Example 4

The following example shows the versatility of unichr() function by creating Unicode characters for both ASCII code point "97" and a non-ASCII code point "8364" −

Open Compiler
ascii_char = unichr(97) non_ascii_char = unichr(8364) print "The Unicode string obtained for ASCII is:", ascii_char print "The Unicode string obtained for non-ASCII is:", non_ascii_char.encode('utf-8')

Output

We get the output as shown below −

The Unicode string obtained for ASCII is: a
The Unicode string obtained for non-ASCII is: 
python_type_casting.htm
Advertisements