1

I am relatively new to python. As a mini-project, I am creating a program that involves taking one-word two strings and converting each character to their corresponding letter value (e.g A = 1, C = 3, Z = 26). I want to find a way to do this without assigning all 26 letters to a number in a dictionary. Every algorithm I have found online doesn't seem to be working or I don't understand it.

I am completely lost on how to go about this. I would appreciate it if someone could point me in the right direction.

Thanks

6 Answers6

0

You can use ascii code. For example:

num = ord(letter1.lower()) - ord('a') + 1

each character is represented by a number in ascii code. You can convert your letter to ascii code using ord, and subtract from it the ascii code of letter 'a'. All alphabet is sequential in ascii table. I added .lower() since you should split it by two cases, if you have upper case or lower case. Full code will look something like this (given a letter in variable letter1:

if letter`.islower():
   num = ord(letter1) - ord('a') + 1
else:
   num = ord(letter1) - ord('A') + 1

(the +1 is if your start counting from 1 rather then 0)

Community
  • 1
  • 1
Roim
  • 2,986
  • 2
  • 10
  • 25
0

You can use the built in ord function to return the unicode code point (as an integer) for any character.

>>> ord('A')
65

You can subtract an offset from that if you like.

>>> offset = ord('A') - 1
>>> ord('A') - offset
1
>>> ord('B') - offset
2
timgeb
  • 76,762
  • 20
  • 123
  • 145
0

Here:

string = 'hello'
nums = ''

for l in string:
    nums += str(ord(l)-96)+' '

print(nums)

The ord() function returns an integer representing the Unicode character. For example, 'a' in Unicode character is 96, 'b' is 97 and 'c' is 98.

Community
  • 1
  • 1
Red
  • 26,798
  • 7
  • 36
  • 58
0

Use ord:

A='lksdfj'
for c in A:
    print(c,':',ord(c))

Output:

l : 108
k : 107
s : 115
d : 100
f : 102
j : 106
Code Pope
  • 5,075
  • 8
  • 26
  • 68
0

The built-in string module provides strings containing the alphabet. You can use a one-liner to make a dict from letter to number:

import string
letter_to_number = {l:n+1 for (l,n) in zip(string.ascii_uppercase, range(len(string.ascii_uppercase)))}
# {'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}
Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53
0

for example...

letter = 'c'
print(ord(letter)-96)
jv95
  • 681
  • 4
  • 18