Python ord()
is a built-in function that returns the Unicode code point of a specified character. It takes a single argument, which can be a string of one character or a single character enclosed in single or double quotes. The ord()
function is useful when working with Unicode characters, as it allows you to convert them to their corresponding integer values.
How to Use Python ord
?
The syntax for using the ord()
function is as follows:
ord(character)
Where character
is the character whose Unicode code point you want to find.
Example 1: Using ord()
with a single character
print(ord('A'))
Output:
65
In this example, the ord()
function returns the Unicode code point of the character ‘A’, which is 65.
Example 2: Using ord()
with a string
print(ord('hello'[0]))
Output:
104
In this example, the ord()
function returns the Unicode code point of the first character in the string ‘hello’, which is ‘h’. The Unicode code point of ‘h’ is 104.
Example 3: Using ord()
with a non-ASCII character
print(ord('é'))
Output:
233
In this example, the ord()
function returns the Unicode code point of the character ‘é’, which is 233.
Example 4: Using ord()
with escape characters
print(ord('\n'))
Output:
10
In this example, the ord()
function returns the Unicode code point of the newline character ‘\n’, which is 10.
Example 5: Using ord()
with a variable
x = 'B'
print(ord(x))
Output:
66
In this example, the ord()
function returns the Unicode code point of the character ‘B’, which is 66. The character is stored in the variable x
.
Related Concepts and Methods
chr()
The chr()
function is the inverse of the ord()
function. It takes an integer Unicode code point and returns the corresponding character. The syntax for using the chr()
function is as follows:
chr(integer)
Where integer
is the Unicode code point you want to convert to a character.
Example: Using chr()
print(chr(65))
Output:
A
In this example, the chr()
function returns the character corresponding to the Unicode code point 65, which is ‘A’.
Unicode
Unicode is a standard for encoding, representing, and handling text in various writing systems. It assigns a unique number to every character in every language. Python supports Unicode natively, which means you can use Unicode characters in your code and manipulate them using built-in functions like ord()
and chr()
.
Conclusion
Python ord()
is a useful built-in function that allows you to find the Unicode code point of a specified character. You can use it to work with Unicode characters and perform various text-related operations. The chr()
function is the inverse of ord()
and can be used to convert Unicode code points back to characters. Understanding Unicode and how to work with Unicode characters is essential for any Python developer working with text data.