首页 文章

如何获取字符的ASCII值?

提问于
浏览
844

如何在Python中将ASCII值作为 int

4 回答

  • 1100

    来自here

    function ord()将获取char的int值 . 如果你想在使用数字后转换回来,函数chr()就可以了 .

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

    在Python 2中,还有 unichr 函数,返回Unicode字符,其序号为 unichr 参数:

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

    在Python 3中,您可以使用 chr 而不是 unichr .


    ord() - Python 3.6.5rc1 documentation

    ord() - Python 2.7.14 documentation

  • 20

    请注意 ord() 不't give you the ASCII value per se; it gives you the numeric value of the character in whatever encoding it' s . 因此,如果您使用Latin-1, ord('ä') 的结果可以是228,或者如果您使用的是UTF-8,它可以引发 TypeError . 如果你传递一个unicode,它甚至可以返回Unicode代码点:

    >>> ord(u'あ')
    12354
    
  • 43

    您正在寻找:

    ord()
    
  • 147

    接受的答案是正确的,但如果您需要将一大堆ASCII字符一次转换为ASCII码,则可以采用更聪明/有效的方法 . 而不是做:

    for ch in mystr:
        code = ord(ch)
    

    或稍快一点:

    for code in map(ord, mystr):
    

    您转换为直接迭代代码的Python本机类型 . 在Python 3上,它是微不足道的:

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

    在Python 2.6 / 2.7上,它's only slightly more involved because it doesn'有一个Py3样式的 bytes 对象( bytesstr 的别名,按字符迭代),但它们确实有 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'):
    

    编码作为按顺序原生迭代的类型意味着转换速度更快;在Py2.7和Py3.5的局部测试中,迭代 str 以使用 map(ord, mystr) 获取其ASCII代码,比使用Py2上的 bytearray(mystr) 或Py3上的 mystr.encode('ascii') 大约需要两倍的长度,并且 str 得到 str 更长时间,为 map(ord, mystr) 支付的乘数上升到~6.5x-7x .

    唯一的缺点是转换是一次性的,所以你的第一个结果可能需要更长的时间,真正巨大的 str 会有一个比例大的临时 bytes / bytearray ,但除非这会迫使你进行页面颠簸,这不是可能很重要 .

相关问题