How do I get the ASCII value of a character as an int
in Python?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
From here:
In Python 2, there is also the
unichr
function, returning the Unicode character whose ordinal is theunichr
argument:In Python 3 you can use
chr
instead ofunichr
.ord() - Python 3.6.5rc1 documentation
ord() - Python 2.7.14 documentation
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 oford('ä')
can be 228 if you're using Latin-1, or it can raise aTypeError
if you're using UTF-8. It can even return the Unicode codepoint instead if you pass it a unicode:You are looking for:
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:
or the slightly faster:
you convert to Python native types that iterate the codes directly. On Python 3, it's trivial:
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 forstr
, which iterates by character), but they do havebytearray
: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 usingmap(ord, mystr)
starts off taking about twice as long for alen
10str
than usingbytearray(mystr)
on Py2 ormystr.encode('ascii')
on Py3, and as thestr
gets longer, the multiplier paid formap(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 temporarybytes
/bytearray
, but unless this forces you into page thrashing, this isn't likely to matter.