Python 2中的Chr行为很奇怪

问题描述 投票:1回答:1

查看Python 2.7]中的chr文档:]

返回一个字符,其ASCII码为整数i的字符串。

source

但是ASCII的范围是128。但是在Python 2.7中,我有:

> chr(181)
'\xb5

这令人惊讶,我预料会出错。我现在暂时接受。

Python 3.7

:中

返回表示Unicode代码点为整数i的字符的字符串。

source

所以基本上,这是Python 2.7中的unichr

Python 3.7

:中
> chr(181).encode('ascii')
UnicodeEncodeError: 'ascii' codec can't encode character '\xb5' in position 0: ordinal not in range(128)

期望,然后:

> chr(181).encode('utf8')
b'\xc2\xb5'

注意我们如何共同使用\xb5

问题

为什么Python 2.7不会在chr(181)上中断,以及它为什么实际上输出似乎是部分正确的编码。

查看Python 2.7中的chr文档:返回一个字符串,该字符串的ASCII码为整数i。源,但ASCII的范围是128。但是在Python 2.7中,我有:> chr(181)'...

python python-2.7 ascii python-unicode
1个回答
1
投票

因为chr()接受的范围是0..255。

© www.soinside.com 2019 - 2024. All rights reserved.