请注意 ord()
并不是直接给你 ASCII 值;它会给出字符在任何编码下的数值。因此,ord('ä')
的结果在使用 Latin-1 编码时可能为 228,或者在使用 UTF-8 编码时可能引发一个 TypeError
异常。甚至如果你传递一个 Unicode 字符,它也可能返回 Unicode 码点。
>>> ord(u'あ')
12354
unicode
。Python3 (bytes):str(b'\xc3\x9c', 'ascii')
-> 报错 _UnicodeDecodeError_。
Python3 (bytes): str(b'\xc3\x9c', 'utf-8')
-> 返回 _Ü_。您还可以查看six包。 - nosahama您正在寻找:
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码开始时,对于长度为10的str
,所花费的时间大约是使用Py2上的bytearray(mystr)
或Py3上的mystr.encode('ascii')
的两倍,随着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]
ord
快上几个数量级。int
,这将返回字符所在编码的相应数值。import numpy as np
# if the characters are in a list
lst = ['a', 'ä', 'あ']
ary = np.array(lst).view(int).tolist() # [97, 228, 12354]
# if the characters are in a string
s = 'abc'
ar = np.array([s])
v = s_arr.view(int) # array([97, 98, 99])
ar
中的所有字符转换为大写,我们可以通过操作v
来实现。v -= 32
print(ar) # ['ABC']
cp1251
(西里尔文)编码的,则使用latin1
并不是一个明智的选择。 - John Machinchr(31415) -> '窷'
- Williamchr(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的。 - jfs