MikeN
MikeN

Reputation: 46267

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

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]

Upvotes: 29

Views: 43679

Answers (7)

Robert
Robert

Reputation: 1631

If you like it short, try the lambda notation:

>>> A = lambda c: chr(ord('a')+c)
>>> A(5)
'f'

Upvotes: 0

gnud
gnud

Reputation: 78518

chr(ord('a')+5)

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

Upvotes: 4

Parappa
Parappa

Reputation: 7676

You need to use the ord function, like

print(ord('a')-5)

Edit: gah, I was too slow :)

Upvotes: 1

codedude
codedude

Reputation: 71

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'

Upvotes: 3

jfs
jfs

Reputation: 414139

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'

Upvotes: 1

gimel
gimel

Reputation: 86354

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

Upvotes: 39

Thomas
Thomas

Reputation: 181735

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

chr(ord('a') + 5)

is the letter 'f'.

Upvotes: 75

Related Questions