How to Convert Letters to Numbers in Python
To convert letters to their corresponding number in the alphabet, use the python ord()
function and subtract 96 from the output.
To demonstrate this, let's loop through a string of letters and create a new array containing numbers.
letters = "zjkswa"
numbers = []
for l in letters:
numbers.append(ord(l) - 96)
print(numbers)
[26, 10, 11, 19, 23, 1]
With list Comprehension
The same conversion as above can be done in one line using list comprehension.
letters = "zjkswa"
numbers = [ord(l) - 96 for l in letters]
print(numbers)
[26, 10, 11, 19, 23, 1]
alphabet