How to get the ASCII value of a character?


How do I get the ASCII value of a character as an int in Python?

10/10/2018 5:24:10 PM

Accepted Answer

From here:

function ord() would get the int value of the char. And in case you want to convert back after playing with the number, function chr() does the trick.

>>> ord('a')
>>> chr(97)
>>> chr(ord('a') + 3)

In Python 2, there is also the unichr function, returning the Unicode character whose ordinal is the unichr argument:

>>> unichr(97)
>>> unichr(1234)

In Python 3 you can use chr instead of unichr.

ord() - Python 3.6.5rc1 documentation

ord() - Python 2.7.14 documentation

3/26/2018 12:42:14 PM

Note that ord() doesn't give you the ASCII value per se; it gives you the numeric value of the character in whatever encoding it's in. Therefore the result of ord('ä') can be 228 if you're using Latin-1, or it can raise a TypeError if you're using UTF-8. It can even return the Unicode codepoint instead if you pass it a unicode:

>>> ord(u'あ')

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow