python2和3中,chr()函数的用法
chr()函数
python内置函数chr(),可以将参数指定的数值,可以是10进制也可以是16进制的值,转换为Unicode字符串。python2和Python3两个版本中,chr()函数的用法有所不同,其中python3版本的源码中对于chr()函数的介绍如下:
chr(i, /)
Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
python2版本的源码中对chr()函数的介绍为:
chr(i) -> character
Return a string of one character with ordinal i; 0 <= i < 256.
即两个版本中,参数i的取值范围有所不同,在python2版本中,如果参数i小于0或大于等于256,python会抛出ValueError。
参数
参数 | 描述 |
---|---|
i | python2为0 <= i < 256,python3中为0 <= i <= 0x10ffff |
返回值
Unicode string。
不同版本python的chr()函数实例代码
Python 3.7.6 (default, Jan 8 2020, 13:42:34)
[Clang 4.0.1 (tags/RELEASE_401/final)] :: Anaconda, Inc. on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> chr(256) #python3版本传递的数等于256,大于255
'Ā'
>>> chr(0x100) #0x100是十进制256的16进制表达方式
'Ā'
Python 2.7.10 (default, Oct 23 2015, 19:19:21)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> chr(256) #python2中传递的参数等于256
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: chr() arg not in range(256)
>>> chr(255)
'\xff'