Last modified: Feb 18, 2026 By Alexander Williams
Python Letter to Number Conversion Guide
Converting letters to numbers is a common task in programming. In Python, this process is straightforward and powerful. It is essential for data encoding, cryptography, and algorithm design.
This guide will show you the best methods. You will learn how to use built-in functions and custom logic. We will cover practical examples and common use cases.
Why Convert Letters to Numbers?
There are many reasons to map letters to numeric values. A common use is creating simple ciphers or encoding schemes. It is also useful for sorting algorithms and data normalization.
For example, you might need to calculate a checksum. Or you may want to assign a unique ID based on a name. Understanding this conversion is a key programming skill.
Method 1: Using the ord() Function
The ord() function is Python's built-in tool for this. It returns the Unicode code point of a single character. For standard English letters, this corresponds to the ASCII value.
The letter 'A' has a code point of 65. 'B' is 66, and so on. Lowercase 'a' starts at 97. This method is fast and requires no setup.
# Example: Get the numeric code for letters
letter = 'C'
number = ord(letter)
print(f"The Unicode code point for '{letter}' is: {number}")
# Convert a sequence of letters
word = "Hello"
for char in word:
print(f"{char}: {ord(char)}")
The Unicode code point for 'C' is: 67
H: 72
e: 101
l: 108
l: 108
o: 111
To get a simple 1-26 mapping for 'A'-'Z', you can subtract a base value. For uppercase, subtract 64. For lowercase, subtract 96. This gives you a position in the alphabet.
# Convert uppercase letters to 1-26
uppercase_letter = 'M'
position = ord(uppercase_letter) - 64
print(f"Letter '{uppercase_letter}' is position {position} in the alphabet.")
Letter 'M' is position 13 in the alphabet.
Method 2: Using a Dictionary Mapping
Sometimes you need a custom mapping. A dictionary gives you full control. You can map 'A' to 1, 'B' to 2, or any other value you choose.
This method is clear and explicit. It is perfect when the mapping is not a simple sequence. You can also handle special cases easily.
# Create a custom letter-to-number map
alphabet_map = {
'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5,
'F': 6, 'G': 7, 'H': 8, 'I': 9, 'J': 10,
'K': 11, 'L': 12, 'M': 13, 'N': 14, 'O': 15,
'P': 16, 'Q': 17, 'R': 18, 'S': 19, 'T': 20,
'U': 21, 'V': 22, 'W': 23, 'X': 24, 'Y': 25, 'Z': 26
}
# Convert a word using the map
word = "PYTHON"
numbers = [alphabet_map[char] for char in word]
print(f"The word '{word}' converts to: {numbers}")
The word 'PYTHON' converts to: [16, 25, 20, 8, 15, 14]
You can build this dictionary dynamically. Use a loop with ord() to create it. This keeps your code clean and adaptable.
Method 3: Using the chr() Function for Reverse Conversion
The chr() function does the opposite of ord(). It takes a number and returns the corresponding character. This is crucial for decoding or reversing the process.
If you have a list of numbers from 65 to 90, chr() will give you 'A' through 'Z'. It is the perfect companion to ord().
# Convert numbers back to letters
numbers_list = [80, 89, 84, 72, 79, 78] # Codes for 'PYTHON'
letters = [chr(num) for num in numbers_list]
result_word = ''.join(letters)
print(f"The numbers {numbers_list} convert to the word: '{result_word}'")
The numbers [80, 89, 84, 72, 79, 78] convert to the word: 'PYTHON'
Practical Example: Creating a Simple Caesar Cipher
Let's apply these concepts. A Caesar cipher shifts letters by a fixed number. Converting letters to numbers makes this easy. We can use ord() and chr().
The steps are simple. Convert the letter to a number. Add the shift value. Handle wrap-around from 'Z' back to 'A'. Convert the new number back to a letter.
def caesar_cipher(text, shift):
"""Encrypts text using a Caesar cipher with the given shift."""
encrypted_text = ""
for char in text:
if char.isupper():
# Shift uppercase letters
shifted_code = (ord(char) - 65 + shift) % 26 + 65
encrypted_text += chr(shifted_code)
elif char.islower():
# Shift lowercase letters
shifted_code = (ord(char) - 97 + shift) % 26 + 97
encrypted_text += chr(shifted_code)
else:
# Keep non-letters the same
encrypted_text += char
return encrypted_text
# Example usage
original = "Hello, World!"
shift = 3
encrypted = caesar_cipher(original, shift)
print(f"Original: {original}")
print(f"Encrypted (shift={shift}): {encrypted}")
Original: Hello, World!
Encrypted (shift=3): Khoor, Zruog!
This example shows the power of letter-number conversion. It is the foundation of many text-based algorithms. Mastering it opens many doors.
Handling Errors and Edge Cases
Your code must be robust. What if the input is not a single letter? Or if it's a number or symbol? You should validate input and handle errors gracefully.
Use .isalpha() to check for letters. Use try-except blocks when using dictionary lookups. Always plan for unexpected input.
def safe_letter_to_number(char):
"""Safely converts a single character to its 1-26 position."""
if len(char) != 1:
return "Error: Input must be a single character."
if not char.isalpha():
return "Error: Input must be a letter (A-Z or a-z)."
# Convert to uppercase for consistent mapping
upper_char = char.upper()
number = ord(upper_char) - 64
return number
# Test the function
print(safe_letter_to_number('G')) # Valid letter
print(safe_letter_to_number('g')) # Lowercase letter
print(safe_letter_to_number('7')) # Digit
print(safe_letter_to_number('AB')) # String longer than 1
7
7
Error: Input must be a letter (A-Z or a-z).
Error: Input must be a single character.
Conclusion
Converting letters to numbers in Python is a fundamental skill. The ord() and chr() functions are your primary tools. They are efficient and built into the language.
For custom mappings, a dictionary is the best choice. It offers clarity and flexibility. Remember to handle errors and edge cases in your projects.
This technique is useful in data science, cryptography, and web development. Practice with the examples provided. You will soon use this conversion with confidence.