Convert Alphabet Letters to Number in Python

How do I convert letters to their corresponding number value?

for example...

letter = 'c'
print(ord(letter)-96)

How to convert letters to numbers using python

I am guessing the code you are using is , from the other link you gave in the question -

print [ord(char) - 96 for char in raw_input('Write Text: ').lower()]

This , as you already found out in your example, would convert all the characters to their unicode counterparts,if you do not want want to convert numbers you can use the following -

>>> print ''.join([str(ord(ch) - 96) if ch.isalpha() else ch for ch in raw_input('Write Text: ').lower()])
Write Text: abcd123 @!#as1
1234123 @!#1191

Conversion of alphabet into numerical values

Use ord(character) to get the value for each letter

string = 'SDFJNKSJDFOSN'
count = 0
for letter in string:
print(f'{ord(letter)=}')

print('\nOr outputs as a list\n')

letter_codes = []
for letter in string:
letter_codes.append(ord(letter))
print(letter_codes)

output

ord(letter)=83
ord(letter)=68
ord(letter)=70
ord(letter)=74
ord(letter)=78
ord(letter)=75
ord(letter)=83
ord(letter)=74
ord(letter)=68
ord(letter)=70
ord(letter)=79
ord(letter)=83
ord(letter)=78

Or outputs as a list

[83, 68, 70, 74, 78, 75, 83, 74, 68, 70, 79, 83

Convert letter into numeric value

You can use dict comprehension:

df = df.replace({'letter_column': {chr(i + 64): i for i in range(1, 27)}})


Related Topics



Leave a reply



Submit