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.....

  • 2
    possible duplicate of [ASCII value of a character in python](http://stackoverflow.com/questions/227459/ascii-value-of-a-character-in-python) – moinudin Nov 30 '10 at 22:35

6 Answers6

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'
moinudin
  • 134,091
  • 45
  • 190
  • 216
  • Good answer, just wanted to point out it's case-sensitive. Might want to add a call to `lower()` to be safe. – Karl Bielefeldt Nov 30 '10 at 22:39
  • 1
    @Laurence: It seems it has been done, although I wouldn't lose too much sleep over it: http://mail.python.org/pipermail/python-dev/2007-October/074991.html – Thomas K Nov 30 '10 at 23:49
5

Just:

ord(c)%32

which can handle both upper and lower.

Kabie
  • 10,489
  • 1
  • 38
  • 45
1

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

ord(c) - ord('A') + 1
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
0
>>> alphadict = dict((x, i + 1) for i, x in enumerate(string.ascii_lowercase))
>>> alphadict['a']
1
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
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.

DGH
  • 11,189
  • 2
  • 23
  • 24
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.

MilkyWay90
  • 2,023
  • 1
  • 9
  • 21