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]
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.
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.
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' >>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With