开发者

Python code for calculating number of an alphabet

开发者 https://www.devze.com 2023-01-27 22:15 出处:网络
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

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) 开发者_JAVA技巧to find it other than declaring a dictionary of 26 alphabets with their respected values.

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


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'


Just:

ord(c)%32

which can handle both upper and lower.


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

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


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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消