1362

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

7 Answers 7

1812

From here:

The function ord() gets 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'
>>>

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

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

In Python 3 you can use chr instead of unichr.


ord() - Python 3.6.5rc1 documentation

ord() - Python 2.7.14 documentation

Sign up to request clarification or add additional context in comments.

6 Comments

which encoding in chr using ?
Note that chr also acts as unichr in Python 3. chr(31415) -> '窷'
@njzk2: it doesn't use any character encoding it returns a bytestring in Python 2. It is upto you to interpret it as a character e.g., chr(ord(u'й'.encode('cp1251'))).decode('cp1251') == u'й'. In Python 3 (or unichr in Python 2), the input number is interpreted as Unicode codepoint integer ordinal: unichr(0x439) == '\u0439' (the first 256 integers has the same mapping as latin-1: unichr(0xe9) == b'\xe9'.decode('latin-1'), the first 128 -- ascii: unichr(0x0a) == b'\x0a'.decode('ascii') it is a Unicode thing, not Python).
Why is the function called "ord"?
@eLymar: it's short for "ordinal," which has similar linguistic roots to "order" - i.e. the numeric rather than symbolic representation of the character
|
191

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

3 Comments

How can you find out which encoding you are using in a given situation?
@Moustache : In Python3, you'll be using Unicode out-of-the-box.
Depends on the object type. Python3 (str): unicode by default. Python3 (bytes): str(b'\xc3\x9c', 'ascii') -> raises UnicodeDecodeError. Python3 (bytes): str(b'\xc3\x9c', 'utf-8') -> returns Ü. You can also look into the six package.
72

You are looking for:

ord()

Comments

47

The accepted answer is correct, but there is a more clever/efficient way to do this if you need to convert a whole bunch of ASCII characters to their ASCII codes at once. Instead of doing:

for ch in mystr:
    code = ord(ch)

or the slightly faster:

for code in map(ord, mystr):

you convert to Python native types that iterate the codes directly. On Python 3, it's trivial:

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

and on Python 2.6/2.7, it's only slightly more involved because it doesn't have a Py3 style bytes object (bytes is an alias for str, which iterates by character), but they do 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'):

Encoding as a type that natively iterates by ordinal means the conversion goes much faster; in local tests on both Py2.7 and Py3.5, iterating a str to get its ASCII codes using map(ord, mystr) starts off taking about twice as long for a len 10 str than 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.

The only downside is that the conversion is all at once, so your first result might take a little longer, and a truly enormous str would have a proportionately large temporary bytes/bytearray, but unless this forces you into page thrashing, this isn't likely to matter.

Comments

7

To get the ASCII code of a character, you can use the ord() function.

Here is an example 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]

Comments

2

You wanted to find out ASCII value of character. Now Im providing the code of ASCII value of a Character:

Code pattern in python: ord(character)

Code Example in python: ord('A') Output: enter image description here

Im providing the code of convert ASCII value to a Character:

Code pattern in python: chr(ASCII value)

Code Example in python: chr(66)

Output: enter image description here

Comments

1

Numpy can also be used to get the ascii value of a character. It is particularly useful if you need to convert a lot of characters to their ascii/unicode codepoints. Depending on the number of characters, it could be orders of magnitude faster than calling ord in a loop.

To use it, wrap a string/character in a numpy array and view it as int, which returns the corresponding numeric value(s) of the character(s) in whatever encoding it is in.

import numpy as np

# if the characters are in a list
lst = ['a', 'ä', 'あ']
ary = np.array(lst).view(int).tolist()   # [97, 228, 12354]


# if the characters are in a string
s = 'abc'
ar = np.array([s])
v = s_arr.view(int)                      # array([97, 98, 99])

As a side note: One feature of the view is that if you change the view, the original changes as well. For example, if we want to make all characters in ar upper case, we could do so by working on v:

v -= 32
print(ar)   # ['ABC']

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.