Python 數字類型轉換


Python數字類型轉換:

  int(x):將 x 轉換為一個整數

  float(x):將 x 轉換為一個浮點數

  complex(x,y):將 x 和 y 轉換為一個復數。x 為復數的實部,y 為復數的虛部。

  eval(x):將 x 轉化為一個整數

  chr(x):x 為數字,將數字轉化為對應的 ASCII 碼。 65 -> A  、90 -> Z 

  ord(x):x 為單個字符,將字符轉換為對應的整數。 a -> 97、122 -> z

# 將 float 浮點型轉化成 int 長整型 num_float = 3.5 print(num_float) # 3.5 print(type(num_float)) # <class 'float'> num_int = int(num_float) print(num_int) # 3 print(type(num_int)) # <class 'int'> # 將 2,3 轉化為復數 num_complex = complex(2,3) print(num_complex) # (2+3j) print(type(num_complex)) # <class 'complex'> # 將字符串轉化為數字類型 str_num = '789' num = eval(str_num) print(num) # 789 print(type(num)) # <class 'int'> # 將整數轉化為字符。 print(chr(65)) # A print(chr(90)) # Z print(chr(97)) # a print(chr(122)) # z # 將字符轉化為整數。 print(ord('A')) # 65

2020-02-06

 


免責聲明!

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



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