python 中進制轉換及format(),int()函數用法


python中數值型變量好像只能是十進制形式表示,其他類型變量只能以字符串形式存在,可以通過format函數將int類型變量轉換成其他進制字符串,如下所示:

v_code=15
# 2進制
x=format(v_code, '#b')  # '0b1111'  等效於:x=bin(v_code)
y=format(v_code, 'b')   # '1111'
# 8進制 x=format(v_code, '#o') # '0o17', 等效於:x=oct(v_code) y=format(v_code, 'o') # '17' # 16進制 x=format(v_code, '#x') # '0xf', 等效於:x=hex(v_code) y=format(v_code, 'x') # 'f' z=format(v_code, '#X') # 'OXF' z=format(v_code, 'X') # 'F'

其中,通過格式符#決定是否顯示前置符號,通過f和F決定16進制中字符的大小寫。

將其他進制字符串轉換成10進制數,用到函數int,如下:

z='F'
x=int(z,16)  #將16進制字符串轉換為int值

其中進制可選2,10,8,16,而缺省時為10.

 


免責聲明!

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



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