chr
, ord
, and ascii
, are built-in functions in the Python programming language. They are used to convert and represent characters and strings, specifically Unicode and ASCII character sets.
chr
This function returns a string representing a character whose Unicode code point is the integer parameter. In Python, every character is associated with a unique number known as Unicode. The chr
function takes an integer between 0 and 1,114,111 as an argument and returns the corresponding character. For example, chr(97)
will return the string ‘a’ because ‘a’ is the character assigned to the Unicode point 97.
Here is how it’s used:
print(chr(97)) # Output: a
Example 1:
print(chr(65)) # Output: 'A'
In this example, the Unicode for the character ‘A’ is 65. So, the chr
function returns ‘A’.
Example 2:
print(chr(8364)) # Output: '€'
The Unicode code point for the Euro sign (€) is 8364. When we pass 8364 to the chr
function, it returns ‘€’.
ord
This function is the inverse of chr
. It takes a string of a single Unicode character as its parameter and returns an integer representing the Unicode code point of that character. For example, ord('a')
will return 97 because ‘a’ corresponds to the Unicode point 97.
Here is how it’s used:
print(ord('a')) # Output: 97
Example 1:
print(ord('Z')) # Output: 90
In this example, the Unicode for the character ‘Z’ is 90. So, the ord
function returns 90.
Example 2:
print(ord('€')) # Output: 8364
The Unicode code point for the Euro sign (€) is 8364. When we pass ‘€’ to the ord
function, it returns 8364.
ascii
This function returns a string that represents a printable version of an object. It escapes the non-ASCII characters in the string using \x
, \u
or \U
escapes. This is useful when you want to print an object that may contain non-ASCII characters and want to ensure they are displayed in a readable way.
Here is how it’s used:
print(ascii('a')) # Output: 'a'
print(ascii('√')) # Output: '\u221a'
As the second example shows, the square root symbol (√) is ‘\u221a’ in ASCII.
Example 1:
print(ascii('Python')) # Output: 'Python'
In this example, all the characters in ‘Python’ are ASCII characters, so the ascii
function just returns the original string ‘Python’.
Example 2:
print(ascii('Python™')) # Output: 'Python\u2122'
In this example, the trademark symbol (™) is not an ASCII character. So the ascii
function returns it as an escaped sequence ‘\u2122’, which is the Unicode for the trademark symbol.
These functions are useful when dealing with characters and their corresponding ASCII or Unicode representations in Python.”