Python ord() and chr() - Get a character and integer value

The ord returns the integer value of a character in Python.

m = ord('m')
n = ord('n')

print(m)  # 109
print(n)  # 110

The chr returns the character representing an integer.

x = chr(109)
y = chr(110)

print(x)  # m
print(y)  # n

Both are Python built-in functions.

The ord() takes a string of length one

x = ord('ab')

# TypeError: ord() expected a character, but string of length 2 found

The ord() can't take a string of length more than one.

The ord() can't take an int

x = ord(1)

# TypeError: ord() expected string of length 1, but int found


Powered by Markdown