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.
Convert Letters to Numbers in Python using ord() method
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)
Output
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))
Output
Traceback (most recent call last):
File "c:\Personal\IJS\Code\main.py", line 4, in <module>
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.
Convert Letters to Numbers in Python using list comprehension
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)
Output
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.