ord function Python
In this post, you will learn about the ord function of Python.
The ord() function of Python converts a character into its Unicode code. The python ord() function takes a string argument of a single Unicode character and returns a number representing the Unicode code point for the given Unicode character. This function is the inverse of chr() for 8-bit strings and of unichr() for Unicode objects.
Sometimes, we may face a situation where we need to convert a character into its related Unicode code. For instance, you may be updating a profile in Python that needs to check each string for emojis and other special characters. These characters are not permitted to be utilized in the form. The ord() function is responsible for converting a character into an integer that represents the Unicode code of the character.
Syntax of ord()
ord(character)
Here, the character is a single string of length 1.
Example of ord()
The given example shows the working of the ord() function.
print("Code point of 4 : ",ord('4'))
print("Code point of A : ",ord('A'))
print("Code point of C : ",ord('C'))
print("Code point of $ : ",ord('$'))
print("Code point of & : ",ord('&'))
Output of the above code -
Code point of 4 : 52
Code point of A : 65
Code point of C : 67
Code point of $ : 36
Code point of & : 38
The length of the string should always be one. If it isn't equivalent to 1, then it will raise TypeError error.
print("Code point of AB : ",ord('AB'))
print("Code point of 30 : ",ord('30'))
Output of the above code -
Traceback (most recent call last):
File "C:\python37\Scripts\projects\test.py", line 1, in
print("Code point of AB : ",ord('AB'))
TypeError: ord() expected a character, but string of length 2 found
Related Articles
zip function in Python
Python multiline string
glob in Python
Python heap implementation
zip function in Python
Remove last element from list Python
Check if list is empty Python
Remove element from list Python
Python split multiple delimiters
Python loop through list
Python iterate list with index
Python add list to list
Python random choice
Python dict inside list
Remove character from string Python
Python compare two lists
Insert data in MySQL database from an HTML form using Django
Alphabet pattern programs in Python