从 here:
函数 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
请注意,ord()
本身并没有给您 ASCII 值;它以任何编码为您提供字符的数值。因此,如果您使用的是 Latin-1,则 ord('ä')
的结果可能是 228,或者如果您使用的是 UTF-8,它可以引发 TypeError
.如果您将 Unicode 传递给它,它甚至可以返回 Unicode 代码点:
>>> ord(u'あ')
12354
unicode
。 Python3(字节):str(b'\xc3\x9c', 'ascii')
->引发 UnicodeDecodeError。 Python3(字节):str(b'\xc3\x9c', 'utf-8')
->返回 Ü。您还可以查看 six 包。
您正在寻找:
ord()
公认的答案是正确的,但是如果您需要一次将一大堆 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 上,它只是稍微复杂一些,因为它没有 Py3 样式的 bytes
对象(bytes
是 str
的别名,它按字符迭代),但它们确实有 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 的本地测试中,使用 map(ord, mystr)
迭代 str
以获取其 ASCII 代码的时间大约是在 Py2 上使用 bytearray(mystr)
的 len
10 str
的两倍或 mystr.encode('ascii')
在 Py3 上,随着 str
变长,为 map(ord, mystr)
支付的乘数上升到 ~6.5x-7x。
唯一的缺点是转换是一次性完成的,因此您的第一个结果可能需要更长的时间,而且真正巨大的 str
会具有相应大的临时 bytes
/bytearray
,但除非这迫使您进入页面颠簸,这可能无关紧要。
要获取字符的 ASCII 码,可以使用 ord()
函数。
这是一个示例代码:
value = input("Your value here: ")
list=[ord(ch) for ch in value]
print(list)
输出:
Your value here: qwerty
[113, 119, 101, 114, 116, 121]
不定期副业成功案例分享
chr(31415) -> '窷'
chr(ord(u'й'.encode('cp1251'))).decode('cp1251') == u'й'
。在 Python 3(或 Python 2 中的unichr
)中,输入数字被解释为 Unicode 码位整数序数:unichr(0x439) == '\u0439'
(前 256 个整数与 latin-1 具有相同的映射:unichr(0xe9) == b'\xe9'.decode('latin-1')
,前 128 个 - ascii:unichr(0x0a) == b'\x0a'.decode('ascii')
它是一个 Unicode 的东西,而不是 Python)。