Coder Perfect

How to find a character’s ASCII value

Problem

In Python, how can I get the ASCII value of a character as an int?

Asked by Matt

Solution #1

From here:

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

The unichr method in Python 2 returned the Unicode character whose ordinal was the unichr argument:

>>> unichr(97)
u'a'
>>> unichr(1234)
u'\u04d2'

You can use chr instead of unichr in Python 3.

Python 3.6.5rc1 documentation for ord()

Python 2.7.14 documentation for ord()

Answered by Matt J

Solution #2

Note that ord() does not return the ASCII value; instead, it returns the character’s numeric value in whatever encoding it is in. If you’re using Latin-1, the result of ord(‘ä’) can be 228; if you’re using UTF-8, it can produce a TypeError. If you supply it a unicode: parameter, it will return the Unicode codepoint instead.

>>> ord(u'あ')
12354

Answered by Ignacio Vazquez-Abrams

Solution #3

What you’re looking for is:

ord()

Answered by Jacob Krall

Solution #4

The approved answer is correct, but if you need to convert a large number of ASCII characters to their ASCII codes at once, there is a more clever/efficient way to do it. rather than doing:

for ch in mystr:
    code = ord(ch)

or the significantly quicker version:

for code in map(ord, mystr):

You transform the code to Python native types, which iterate it directly. It’s simple in Python 3:

for code in mystr.encode('ascii'):

It’s just slightly more complicated in Python 2.6/2.7 because it lacks a Py3-style bytes object (bytes is an alias for str, which iterates by character), but it does have bytearray:

# If mystr is definitely str, not unicode
for code in bytearray(mystr):

# If mystr could be either str or unicode
for code in bytearray(mystr, 'ascii'):

Iterating a str to get its ASCII codes using map(ord, mystr) takes around twice as long for a len 10 str as using bytearray(mystr) on Py2 or mystr.encode(‘ascii’) on Py3, and as the str gets longer, the multiplier paid for map(ord, mystr) rises to 6.5x-7x in local tests on both Py2.7 and Py3.5.

The main drawback is that the conversion happens all at once, so your initial result would take a bit longer, and a genuinely massive str would have a similarly large temporary bytes/bytearray, but this is unlikely to be an issue until you’re forced into page thrashing.

Answered by ShadowRanger

Solution #5

The ord() function can be used to obtain a character’s ASCII code.

As an example, consider the following code:

value = input("Your value here: ")
list=[ord(ch) for ch in value]
print(list)

Output:

Your value here: qwerty
[113, 119, 101, 114, 116, 121]

Answered by Indi

Post is based on https://stackoverflow.com/questions/227459/how-to-get-the-ascii-value-of-a-character