In this tutorial, we will learn how to print Unicode characters in Python 3. Unicode is an encoding standard that assigns a unique code point to each character for consistent representation and manipulation of text across various platforms and languages.
Python 3 supports Unicode natively, making it easier to handle text in different languages and scripts. Let’s explore the steps to print Unicode characters in Python 3.
Step 1: Getting the Unicode code point of a character
In Python 3, you can use the ord() function to obtain the Unicode code point of a given character. This function takes a single string argument, representing the character you want the Unicode code point for, and returns an integer value representing the code point. For example:
1 2 3 |
char = 'A' code_point = ord(char) print(code_point) |
Output:
65
Step 2: Converting Unicode code points to characters
You can obtain the corresponding character for a Unicode code point using the chr() function in Python 3. The function takes an integer argument, representing the Unicode code point, and returns a single-character string. For example:
1 2 3 |
code_point = 65 char = chr(code_point) print(char) |
Output:
A
Step 3: Print Unicode characters
Now that we know how to obtain Unicode code points and convert them to characters, we can print Unicode characters in Python 3 programs. To do this, you can use the print() function and pass Unicode strings directly or print the characters obtained from the chr() function.
Unicode strings in Python 3 can be declared using the u prefix before the string. For example:
1 2 3 |
# Unicode string unicode_string = u'こんにちは' print(unicode_string) |
Output:
こんにちは
Alternatively, you can print the characters obtained from the chr() function as follows:
1 2 3 4 5 |
# Unicode code points for a smiley face unicode_code_point = 0x1F600 unicode_char = chr(unicode_code_point) print(unicode_char) |
Output:
😀
Full Code
Here is the full code for printing Unicode characters in Python 3:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
# Obtain the Unicode code point of a character char = 'A' code_point = ord(char) print(code_point) # Convert Unicode code point to character code_point = 65 char = chr(code_point) print(char) # Print Unicode characters # Unicode string unicode_string = u'こんにちは' print(unicode_string) # Unicode character obtained from the chr() function unicode_code_point = 0x1F600 unicode_char = chr(unicode_code_point) print(unicode_char) |
Output:
65 A こんにちは 😀
Conclusion
In this tutorial, we have seen how to print Unicode characters in Python 3 using the ord() and chr() functions. We have also learned how to create Unicode strings and print them directly or print characters obtained from Unicode code points. This functionality makes it easy to work with text in various languages and scripts in Python 3.