tags:

views:

214

answers:

5

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]
+3  A: 

chr(ord('a')+5)

gnud
+17  A: 

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

chr(ord('a') + 5)

is the letter 'f'.

Thomas
... which is the 6th letter in the alphabet, unless you are zero-indexing...
Paul McGuire
It is the 5th letter from `'a'`, obviously. And yes, I'm zero-indexing. What self-respecting programmer doesn't? ;)
Thomas
Also, it is perfectly in line with the examples given in the question.
Thomas
+1  A: 

You need to use the ord function, like print(ord('a')-5)

Edit: gah, I was too slow :)

Parappa
+11  A: 

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'
>>>
gimel
A: 
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'
J.F. Sebastian