
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert Single Character to Integer Value in Python
In Python, the ord() function converts a given character to the corresponding ASCII (American Standard Code for Information Interchange) integer. The ord() function raises a TypeError if you pass a string value as a parameter.
Converting a single alphabet to its integer
In the following example, we have converted a character 'A' into its Unicode using the ord() function -
my_str='A' result=ord(my_str) print("Unicode of 'A'-",result)
Following is an output of the above code -
Unicode of 'A'- 65
Printing Integer values of all the alphabets
We can use the ord() function to print all the Unicode characters of the alphabet by iterating through a for loop.
char_dict = {chr(ch): ord(chr(ch)) for ch in range(ord('A'), ord('Z') + 1)} print(char_dict)
Following is an output of the above code -
{'A': 65, 'B': 66, 'C': 67, 'D': 68, 'E': 69, 'F': 70, 'G': 71, 'H': 72, 'I': 73, 'J': 74, 'K': 75, 'L': 76, 'M': 77, 'N': 78, 'O': 79, 'P': 80, 'Q': 81, 'R': 82, 'S': 83, 'T': 84, 'U': 85, 'V': 86, 'W': 87, 'X': 88, 'Y': 89, 'Z': 90}
Example
In the following example, we have passed a string value resulted in a TypeError.
my_str='St' result=ord(my_str) print(result)
Following is an output of the above code -
Traceback (most recent call last): File "/home/cg/root/89556/main.py", line 2, in <module> result=ord(my_str) ^^^^^^^^^^^ TypeError: ord() expected a character, but string of length 2 found
Advertisements