Get character position in alphabet Get character position in alphabet python python

Get character position in alphabet


It is called index. For e.g.

>>> import string>>> string.lowercase.index('b')1>>> 

Note: in Python 3, string.lowercase has been renamed to string.ascii_lowercase.


Without the import

def char_position(letter):    return ord(letter) - 97def pos_to_char(pos):    return chr(pos + 97)


You can use ord() to get a character's ASCII position, and chr() to convert a ASCII position into a character.

EDIT: Updated to wrap alphabet so a-1 maps to z and z+1 maps to a

For example:

my_string  = "zebra"difference = -1new_string = ''.join((chr(97+(ord(letter)-97+difference) % 26) for letter in my_string))

This will create a string with all the characters moved one space backwards in the alphabet ('ydaqz'). It will only work for lowercase words.