请注意 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代码点:
在Python 2.6 / 2.7上,它's only slightly more involved because it doesn'有一个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'):
4 回答
来自here:
在Python 2中,还有
unichr
函数,返回Unicode字符,其序号为unichr
参数:在Python 3中,您可以使用
chr
而不是unichr
.ord() - Python 3.6.5rc1 documentation
ord() - Python 2.7.14 documentation
请注意
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代码点:您正在寻找:
接受的答案是正确的,但如果您需要将一大堆ASCII字符一次转换为ASCII码,则可以采用更聪明/有效的方法 . 而不是做:
或稍快一点:
您转换为直接迭代代码的Python本机类型 . 在Python 3上,它是微不足道的:
在Python 2.6 / 2.7上,它's only slightly more involved because it doesn'有一个Py3样式的
bytes
对象(bytes
是str
的别名,按字符迭代),但它们确实有bytearray
:编码作为按顺序原生迭代的类型意味着转换速度更快;在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
,但除非这会迫使你进行页面颠簸,这不是可能很重要 .