views:

14257

answers:

3

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

+5  A: 

You are looking for:

ord()
Jacob
+32  A: 

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')
97
>>> chr(97)
'a'
>>> chr(ord('a') + 3)
'd'
>>>

There is also a unichr function, returning the Unicode character whose ordinal is the unichr argument:

>>> unichr(97)
u'a'
>>> unichr(1234)
u'\u04d2'
Matt J
+17  A: 

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'あ')
12354
Ignacio Vazquez-Abrams