Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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] 
like image 333
MikeN Avatar asked Nov 12 '09 18:11

MikeN


People also ask

How do you get the next letter in Python?

To increment a character in a Python, we have to convert it into an integer and add 1 to it and then cast the resultant integer to char. We can achieve this using the builtin methods ord and chr.

How do I get the alphabet value in Python?

Use the ord() Function to Convert Letters to Numbers in Python. The ord() function in Python is utilized to return the Unicode , or in this case, the ASCII value of a given letter of the alphabet. We will apply the ord() function to the letters and subtract 96 to get the accurate ASCII value.


2 Answers

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

chr(ord('a') + 5) 

is the letter 'f'.

like image 113
Thomas Avatar answered Sep 21 '22 09:09

Thomas


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' >>>  
like image 30
gimel Avatar answered Sep 19 '22 09:09

gimel