1

I need to find the number of an alphabet in the range of alphabets ie a = 1, b=2 , c =3.... So if i get a then the returning value should be 1

Is there a shorter method provided in python(inbuilt) to find it other than declaring a dictionary of 26 alphabets with their respected values.

Please help if you know of such a function.....

1

6 Answers 6

7

Use ord()

>>> c = 'f' >>> ord(c) - ord('a') + 1 6 

If you want 'f' and 'F' to both return 6, use lower()

>>> c = 'F' >>> ord(lower(c)) - ord('a') + 1 6 

You might also be interested in chr()

>>> c = 'f' >>> chr(ord(c) + 1) 'g' 
Sign up to request clarification or add additional context in comments.

2 Comments

Good answer, just wanted to point out it's case-sensitive. Might want to add a call to lower() to be safe.
@Laurence: It seems it has been done, although I wouldn't lose too much sleep over it: mail.python.org/pipermail/python-dev/2007-October/074991.html
5

Just:

ord(c)%32 

which can handle both upper and lower.

1 Comment

While obvious in retrospect, I'd not realized (or remembered) that the % 32 would work. Thanks!
1

If you only need A to Z then you can use ord:

ord(c) - ord('A') + 1 

Comments

0
>>> alphadict = dict((x, i + 1) for i, x in enumerate(string.ascii_lowercase)) >>> alphadict['a'] 1 

3 Comments

alphadict = dict(enumerate(string.ascii_lowercase, start=1))
@THC4k: that will reverse the key and value.
@Kabie: Whoops you are right. At least the start part is useful.
0

The function ord('a') will return the numeric value of 'a' in the current text encoding. You could probably take that and do some simple math to convert to a 1, 2, 3 type mapping.

Comments

0

TL;DR

def lettertoNumber(letter): return ord(letter.upper()) - 64 

LONG EXPLANATION

ord(char) returns the Unicode number for that character, but we are looking for a = 1, b = 2, c = 3.

But in Unicode, we get A = 65, B = 66, C = 67.

However, if we subtract 64 from all those letters, we get A = 1, B = 2, C = 3. But that isn't enough, because we need to support lower-case letters too!

Because of lowercase letters, we need to make the letter uppercase using .upper() so then it automatically can use ord() without the result being greater than 26, which gives us the code in the TL;DR section.

Comments