內置函數值 -- chr() ord() -- 字符和ascii的轉換


英文文檔:

chr (i)
  Return the string representing a character whose Unicode code point is the integer i. For example, chr(97) returns the string 'a', while chr(8364) returns the string '€'. This is the inverse of ord().
  The valid range for the argument is from 0 through 1,114,111 (0x10FFFF in base 16). ValueError will be raised if i is outside that range
說明:
  1. 函數返回整形參數值所對應的Unicode字符的字符串表示
復制代碼
>>> chr(97) #參數類型為整數
'a'

>>> chr('97') #參數傳入字符串時報錯
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    chr('97')
TypeError: an integer is required (got type str)

>>> type(chr(97)) #返回類型為字符串
<class 'str'>
復制代碼

  2. 它的功能與ord函數剛好相反

>>> chr(97)
'a'
>>> ord('a')
97

  3. 傳入的參數值范圍必須在0-1114111(十六進制為0x10FFFF)之間,否則將報ValueError錯誤

復制代碼
>>> chr(-1) #小於0報錯
Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    chr(-1)
ValueError: chr() arg not in range(0x110000)

>>> chr(1114111)
'\U0010ffff'

>>> chr(1114112) #超過1114111報錯
Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    chr(1114112)
ValueError: chr() arg not in range(0x110000)
復制代碼

 簡單描述

chr接收一個數字, 找到這個數字對應的ascii里的元素(只能接受數字)
a = chr(65)
print(a) #結果: A

ord()接收一個字符,返回這個字符對應的數字.(只能接受一個字符)
b = ord('a')
print(b) #結果: 97


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM