1202

如何在Python中获取字符的ASCII值?int

4

5 回答 5

1580

这里

该函数ord()获取char的int值。如果您想在使用数字后转换回来,函数chr()可以解决问题。

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

在 Python 2 中,还有一个unichr函数,它返回以序数为参数的Unicodeunichr字符:

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

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


ord() - Python 3.6.5rc1 文档

ord() - Python 2.7.14 文档

于 2008-10-22T20:43:04.443 回答
181

请注意,ord()它本身并没有给你 ASCII 值;它以任何编码为您提供字符的数值。因此,ord('ä')如果您使用的是 Latin-1,则结果可以是 228,或者TypeError如果您使用的是 UTF-8,它可以引发 a。如果您将 Unicode 传递给它,它甚至可以返回 Unicode 代码点:

>>> ord(u'あ')
12354
于 2008-10-22T23:19:20.757 回答
56

您正在寻找:

ord()
于 2008-10-22T20:41:56.817 回答
41

公认的答案是正确的,但是如果您需要一次将一大堆 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 上的本地测试中,迭代 astr以获取其 ASCII 码使用10map(ord, mystr)所花费的时间大约是在 Py2 或Py3上使用的两倍,并且随着时间的延长,乘数会增加到〜6.5x-7x。lenstrbytearray(mystr)mystr.encode('ascii')strmap(ord, mystr)

唯一的缺点是转换是一次完成的,所以你的第一个结果可能需要更长的时间,真正巨大的str会有一个成比例的临时bytes/ bytearray,但除非这迫使你进入页面抖动,否则这可能并不重要.

于 2016-03-25T17:56:08.113 回答
4

要获取字符的 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]
于 2019-11-01T06:21:27.687 回答