- Convert Letters to Numbers in Python
- Convert Letters to Numbers in Python
- Using ord() Method
- Using list comprehension
- Conclusion
- Python letter to int
- # Table of Contents
- # Convert letters to numbers in Python
- # Convert numbers to letters in Python
- # Convert all letters in a string to numbers
- # Convert all letters in a string to numbers using for loop
- # Additional Resources
- Convert Letter to Number in Python
- Use the ord() Function to Convert Letters to Numbers in Python
- Use list comprehension to Convert Letters to Numbers in Python
- Related Article — Python String
- Related Article — Python Number
Convert Letters to Numbers in Python
Using the ord() method, we can convert letters to numbers in Python. The ord() method returns an integer representing the Unicode character.
In this tutorial, we will look at converting letters to numbers in Python with examples.
ASCII (American Standard Code for Information Interchange) is a coding standard that assigns an integer value to every character on the keyboard.
Each character will have its own integer value, and the value differs for uppercase and lowercase characters.
Convert Letters to Numbers in Python
We will be using two different approaches to convert letter to number in this article.
Using ord() Method
The ord() is a built-in method in Python that takes a single character as an input and returns an integer representing the Unicode character.
The following code uses the ord() method to convert each letter to a number.
text= "itsmycode" num_list = [] # iterate each characters in string # and convert to number using ord() for c in text: num_list.append(ord(c) - 96) # print the converted letters as numbers in list print("After converting letters to numbers",num_list)
After converting letters to numbers [9, 20, 19, 13, 25, 3, 15, 4, 5]
The ord() cannot take more than one character as input. If you pass more than one character at a time, you will get a TypeError: ord() expected a character, but string of length 9 found.
text= "itsmycode" num_list = [] print(ord(text))
Traceback (most recent call last): File "c:\Personal\IJS\Code\main.py", line 4, in print(ord(text)) TypeError: ord() expected a character, but string of length 9 found
Using list comprehension
The list comprehension offers a shorter and compact syntax, and it’s an elegant way to create a list based on the existing list.
List comprehension is considered fastest in processing the list when compared to the for loop.
Let us take the same example and modify our code to use list comprehension to convert letters to numbers in Python.
text = "itsmycode" # elegant way using list comprehension num_list = [ord(x) - 96 for x in text] # print the converted letters as numbers in list print("After converting letters to numbers", num_list)
After converting letters to numbers [9, 20, 19, 13, 25, 3, 15, 4, 5]
Conclusion
We can convert letters to numbers in Python using the ord() method. The ord() method takes a single character as an input and return an integer representing the Unicode character.
The string can be iterated through for loop and use an ord() method to convert each letter into number. The more elegant and compact way would be to use list comprehension instead of for loop for better performance.
Python letter to int
Last updated: Feb 22, 2023
Reading time · 5 min
# Table of Contents
# Convert letters to numbers in Python
Use the ord() function to convert a letter to a number, e.g. number = ord(‘a’) .
The ord() function takes a string that represents 1 Unicode character and returns an integer representing the Unicode code point of the given character.
Copied!number = ord('a') print(number) # 👉️ 97 one_based = ord('a') - 96 print(one_based) # 👉️ 1 # ------------------------------------ number = ord('A') print(number) # 👉️ 65 one_based = ord('A') - 64 print(one_based) # 👉️ 1
If you need to convert an integer to its letter equivalent, click on the following subheading:
The ord function takes a string that represents 1 Unicode character and returns an integer representing the Unicode code point of the given character.
Copied!print(ord('a')) # 👉️ 97 print(ord('b')) # 👉️ 98
If you need to get a one-based result instead of the Unicode code point of the character, subtract 96 for lowercase characters or 64 for uppercase characters.
Copied!number = ord('a') print(number) # 👉️ 97 one_based = ord('a') - 96 print(one_based) # 👉️ 1 # ------------------------------------ number = ord('A') print(number) # 👉️ 65 one_based = ord('A') - 64 print(one_based) # 👉️ 1
The lowercase letter a has a Unicode code point of 97, so subtracting 96 gives us a value of 1 .
The chr function is the inverse of ord() .
Copied!print(chr(97)) # 👉️ 'a' print(chr(98)) # 👉️ 'b'
It takes an integer that represents a Unicode code point and returns the corresponding character.
# Convert numbers to letters in Python
Use the chr() function to convert a number to a letter, e.g. letter = chr(97) .
The chr() function takes an integer that represents a Unicode code point and returns the corresponding character.
Copied!# ✅ convert number to letter (standard) letter = chr(97) print(letter) # 👉️ 'a' letter = chr(65) print(letter) # 👉️ 'A' # -------------------------- # ✅ convert number to letter (starting at 1) letter = chr(ord('`') + 1) print(letter) # 👉️ 'a' letter = chr(ord('@') + 1) print(letter) # 👉️ 'A'
The chr function takes an integer that represents a Unicode code point and returns the corresponding character.
For example, lowercase a has a Unicode code point of 97 and uppercase A has a Unicode code point of 65 .
Copied!letter = chr(97) print(letter) # 👉️ 'a' print(chr(98)) # 👉️ 'b' letter = chr(65) print(letter) # 👉️ 'A' print(chr(66)) # 👉️ 'B'
If you need to convert the number 1 to lowercase or uppercase a , use the ord() function in conjunction with chr() .
Copied!letter = chr(ord('`') + 1) print(letter) # 👉️ 'a' letter = chr(ord('@') + 1) print(letter) # 👉️ 'A' print(ord('`')) # 👉️ 96 print(ord('@')) # 👉️ 64
The ord function takes a string that represents 1 Unicode character and returns an integer representing the Unicode code point of the given character.
Copied!print(ord('a')) # 👉️ 97 print(ord('b')) # 👉️ 98
We used the ord() function to get the Unicode code point of the tilde character because it is the last character before the lowercase letter a and added 1 to the result.
Copied!letter = chr(ord('`') + 1) print(letter) # 👉️ 'a' letter = chr(ord('@') + 1) print(letter) # 👉️ 'A' print(ord('`')) # 👉️ 96 print(ord('@')) # 👉️ 64
The @ symbol is the last character before the capital letter A , so adding 1 to the result and calling the chr() function gets us the capital letter A .
Copied!list_of_lowercase_letters = [ chr(i) for i in range(ord('a'), ord('z') + 1) ] # 👇️ ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] print(list_of_lowercase_letters) list_of_uppercase_letters = [ chr(i) for i in range(ord('A'), ord('Z') + 1) ] # 👇️ ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] print(list_of_uppercase_letters)
We used the range() class to get a range that we can iterate over and used a list comprehension to iterate over the range.
List comprehensions are used to perform some operation for every element or select a subset of elements that meet a condition.
You can use list slicing if you need to get a slice of the list of letters.
Copied!letters = [ chr(i) for i in range(ord('a'), ord('z') + 1) ] # 👇️ ['a', 'b', 'c', 'd', 'e', 'f'] print(letters[:letters.index('f') + 1])
The syntax for list slicing is my_list[start:stop:step] .
The start index is inclusive and the stop index is exclusive (up to, but not including).
Python indexes are zero-based, so the first item in a list has an index of 0 , and the last item has an index of -1 or len(my_list) — 1 .
We didn’t specify a start index, so the list slice starts at index 0 .
# Convert all letters in a string to numbers
To convert all of the letters in a string to numbers:
- Use a list comprehension to iterate over the string.
- Use the ord() function to get the Unicode code point of each character.
- The new list will contain the corresponding numbers.
Copied!my_str = 'bobbyhadz' numbers = [ ord(char) - 96 for char in my_str.lower() ] print(numbers) # 👉️ [2, 15, 2, 2, 25, 8, 1, 4, 26]
We used a list comprehension to iterate over the lowercase version of the string.
List comprehensions are used to perform some operation for every element or select a subset of elements that meet a condition.
On each iteration, we use the ord() function to get the Unicode code point of the current letter and subtract 96 to get a one-based result.
If you need to get a list containing the Unicode code points of each character in the string, don’t subtract 96 from each call to ord() .
Copied!my_str = 'bobbyhadz' numbers = [ ord(char) for char in my_str.lower() ] print(numbers) # 👉️ [98, 111, 98, 98, 121, 104, 97, 100, 122]
The new list contains the Unicode code points of the characters in the string.
Alternatively, you can use a for loop.
# Convert all letters in a string to numbers using for loop
This is a three-step process:
- Use a for loop to iterate over the string.
- Use the ord() function to get the Unicode code point of each character.
- Append the results to a new list.
Copied!my_str = 'bobbyhadz' numbers = [] for char in my_str.lower(): numbers.append( ord(char) - 96 ) print(numbers) # 👉️ [2, 15, 2, 2, 25, 8, 1, 4, 26]
We used a for loop to iterate over the lowercase version of the string.
On each iteration, we use the ord() function to get the number that corresponds to the current letter and append the result to a list.
The list.append() method adds an item to the end of the list.
Copied!my_list = ['bobby', 'hadz'] my_list.append('com') print(my_list) # 👉️ ['bobby', 'hadz', 'com']
The method returns None as it mutates the original list.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
Convert Letter to Number in Python
- Use the ord() Function to Convert Letters to Numbers in Python
- Use list comprehension to Convert Letters to Numbers in Python
This tutorial demonstrates the different ways available to convert letters to numbers in Python.
First, let us explain how converting a letter of the alphabet to a number is possible.
The term ASCII , an acronym for American Standard Code for Information Interchange , is essentially a standard capable of assigning letters, numbers, and some other characters in the 8-bit code that contains a maximum of 256 available slots.
Each character, no matter if it is a digit (0-9) or a letter (a-z) or (A-Z) has an ASCII value assigned to it, which can simply be utilized to figure out the number or the value that any letter of the alphabet holds.
To explain this tutorial, we will take a string of letters of the alphabet and convert it to a list of numbers.
Use the ord() Function to Convert Letters to Numbers in Python
The ord() function in Python is utilized to return the Unicode , or in this case, the ASCII value of a given letter of the alphabet. We will apply the ord() function to the letters and subtract 96 to get the accurate ASCII value.
The following code uses the ord() function to convert letters to numbers in Python.
l = "web" n = [] for x in l: n.append(ord(x) - 96) print(n)
The above code provides the following output:
Use list comprehension to Convert Letters to Numbers in Python
List comprehension is a comparatively shorter and refined way to create lists that are to be formed based on the values given of an already existing list.
The code can pretty much be finished with a one-liner by using list comprehension here.
The following code uses list comprehension to convert letters to numbers in Python.
l = "web" n = [ord(x) - 96 for x in l] print(n)
The above code provides the following output:
Vaibhhav is an IT professional who has a strong-hold in Python programming and various projects under his belt. He has an eagerness to discover new things and is a quick learner.
Related Article — Python String
Related Article — Python Number
Copyright © 2023. All right reserved