开发者

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

开发者 https://www.devze.com 2022-12-11 01:53 出处:网络
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 alphabe开发者_开发技巧t without having an array of letters?

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 alphabe开发者_开发技巧t 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]


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

chr(ord('a') + 5)

is the letter 'f'.


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


chr(ord('a')+5)

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


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'


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'


You need to use the ord function, like

print(ord('a')-5)

Edit: gah, I was too slow :)


If you like it short, try the lambda notation:

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

精彩评论

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

关注公众号