How could I print out the nth letter of the alphabet in Python?

Question:

ASCII math doesn’t seem to work in Python:

‘a’ + 5
DOESN’T WORK

How could I quickly print out the nth letter of the alphabet without having an array of letters?

My naive solution is this:

letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
print letters[5]
Asked By: MikeN

||

Answers:

chr(ord('a')+5)

​​​​​​​​​​​​​​​​​​​

Answered By: gnud

chr and ord convert characters from and to integers, respectively. So:

chr(ord('a') + 5)

is the letter 'f'.

Answered By: Thomas

You need to use the ord function, like

print(ord('a')-5)

Edit: gah, I was too slow 🙂

Answered By: Parappa

ASCII math aside, you don’t have to type your letters table by hand.
The string constants in the string module provide what you were looking for.

>>> import string
>>> string.ascii_uppercase[5]
'F'
>>> 
Answered By: gimel
import string
print string.letters[n + is_upper*26]

For example:

>>> n = 5
>>> is_upper = False
>>> string.letters[n+is_upper*26]
'f'
>>> is_upper = True
>>> string.letters[n+is_upper*26]
'F'
Answered By: jfs

if u want to go really out of the way (probably not very good) you could create a new class CharMath:

class CharMath:
    def __init__(self,char):
        if len(char) > 1: raise IndexError("Not a single character provided")
        else: self.char = char
    def __add__(self,num):
        if type(num) == int or type(num) == float: return chr(ord(self.char) + num)
        raise TypeError("Number not provided")

The above can be used:

>>> CharMath("a") + 5
'f'
Answered By: codedude

If you like it short, try the lambda notation:

>>> A = lambda c: chr(ord('a')+c)
>>> A(5)
'f'
Answered By: Robert
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.