chr()方法返回一个字符串,该字符串表示Unicode代码点是整数的字符。句法:
chr(num) num: integer value
- chr()方法仅使用一个整数作为参数。
- 范围可能从0到1,1141,111(以16为底的0x10FFFF)变化。
- chr()方法返回一个字符,其Unicode点为num(整数)。
- 如果传递的整数超出范围,则该方法返回ValueError。
示例:假设我们要打印“ G e e k s f o r G e e k s”。
# Python program to illustrate
# chr() builtin function
print(chr(71), chr(101),
chr(101), chr(107),
chr(115), chr(32),
chr(102), chr(111),
chr(114),chr(32),
chr(71), chr(101),
chr(101), chr(107),
chr(115))
输出:
G e e k s f o r G e e k s
另一个例子:
# Python program to illustrate
# chr() builtin function
numbers = [17, 38, 79]
for number in numbers:
# Convert ASCII-based number to character.
letter = chr(number)
print("Character of ASCII value", number, "is ", letter)
输出:
Character of ASCII value 17 is Character of ASCII value 38 is & Character of ASCII value 79 is O
如果我们超出范围,会发生什么?
# Python program to illustrate
# chr() builtin function
# if value given is
# out of range
# Convert ASCII-based number to character
print(chr(400))
输出:
No Output
我们不会得到任何输出,编译器将抛出错误:
Traceback (most recent call last): File "/home/484c76fb455a624cc137946a244a9aa5.py", line 1, in print(chr(400)) UnicodeEncodeError:'ascii' codec can't encode character '\u0190' in position 0:ordinal not in range(128)
相关用法
注:本文由纯净天空筛选整理自Chinmoy Lenka大神的英文原创作品 chr() in Python。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。