✒️
Start your developer blog today!
✉️
Questions?
Email me

How to Get the ASCII Value of a Character in Python

Sep 18, 2020 1 min read

We can use the ord() and chr() functions in Python to convert between characters and their numeric values, which depends on the encoding it’s in.

Assuming we’re using strings in Python 3, these functions will convert over the unicode encoding.

ord() will give us the integer value of a character.

ord('A') # 65
ord('B') # 66

chr() will give us the character representation of a number.

chr(65) # 'A'
chr(66) # 'B'

Suppose we want 'A' = 1, 'B' = 2,..., 'Z' = 26.

We can get the numeric value of an uppercase letter like so:

def convert(char):
    return ord(char) - ord('A') + 1
convert('A') # 1
convert('Z') # 26

Suppose we want the ith letter of the lowercase alphabet.

def alphabet(offset)
    return chr(ord('a') + offset)
alphabet(3) # 'd'
alphabet(5) # 'f'