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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。