How to get the ASCII value of a character

前端 未结 6 628
天命终不由人
天命终不由人 2020-11-22 07:04

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

6条回答
  •  清歌不尽
    2020-11-22 07:16

    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.

提交回复
热议问题