Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to convert a single character to its integer value in Python?
In Python, the ord() function converts a single character to its corresponding ASCII (American Standard Code for Information Interchange) or Unicode integer value. The ord() function raises a TypeError if you pass a string with more than one character.
Syntax
ord(character)
Parameters: A single character (string of length 1)
Return Value: Integer representing the Unicode code point of the character
Converting a Single Character to Integer
Here's how to convert a character 'A' to its Unicode integer value ?
my_char = 'A'
result = ord(my_char)
print("Unicode of 'A':", result)
# Other examples
print("Unicode of 'a':", ord('a'))
print("Unicode of '5':", ord('5'))
print("Unicode of '@':", ord('@'))
Unicode of 'A': 65 Unicode of 'a': 97 Unicode of '5': 53 Unicode of '@': 64
Converting All Alphabets to Integer Values
You can use the ord() function to get Unicode values for all uppercase letters ?
# Create dictionary of uppercase letters and their Unicode values
char_dict = {chr(ch): ord(chr(ch)) for ch in range(ord('A'), ord('Z') + 1)}
print("Uppercase letters:")
for char, value in list(char_dict.items())[:5]: # Show first 5
print(f"'{char}': {value}")
print("\nLowercase letters (a-e):")
for i in range(5):
char = chr(ord('a') + i)
print(f"'{char}': {ord(char)}")
Uppercase letters: 'A': 65 'B': 66 'C': 67 'D': 68 'E': 69 Lowercase letters (a-e): 'a': 97 'b': 98 'c': 99 'd': 100 'e': 101
Error Handling
The ord() function only accepts single characters. Passing a string with multiple characters raises a TypeError ?
# This will cause an error
try:
my_str = 'St'
result = ord(my_str)
print(result)
except TypeError as e:
print("Error:", e)
# Correct way - process each character
my_str = 'St'
for char in my_str:
print(f"Unicode of '{char}': {ord(char)}")
Error: ord() expected a character, but string of length 2 found Unicode of 'S': 83 Unicode of 't': 116
Common Use Cases
The ord() function is useful for character manipulation, sorting, and encoding tasks ?
# Check if character is uppercase
char = 'M'
if ord('A') <= ord(char) <= ord('Z'):
print(f"'{char}' is uppercase")
# Calculate distance between characters
char1, char2 = 'A', 'E'
distance = ord(char2) - ord(char1)
print(f"Distance from '{char1}' to '{char2}': {distance}")
# Simple Caesar cipher shift
def shift_char(char, shift):
if 'A' <= char <= 'Z':
return chr((ord(char) - ord('A') + shift) % 26 + ord('A'))
return char
original = 'H'
shifted = shift_char(original, 3)
print(f"'{original}' shifted by 3: '{shifted}'")
'M' is uppercase Distance from 'A' to 'E': 4 'H' shifted by 3: 'K'
Conclusion
The ord() function converts single characters to their Unicode integer values. Remember it only accepts single characters, not strings. Use it for character analysis, sorting algorithms, and text encoding operations.
