本文介紹了在python中將整數(shù)轉(zhuǎn)換為二進制的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
為了將整數(shù)轉(zhuǎn)換為二進制,我使用了以下代碼:
In order to convert an integer to a binary, I have used this code :
>>> bin(6)
'0b110'
什么時候刪除'0b',我用這個:
and when to erase the '0b', I use this :
>>> bin(6)[2:]
'110'
如果我想將 6
顯示為 00000110
而不是 110
,該怎么辦?
What can I do if I want to show 6
as 00000110
instead of 110
?
推薦答案
>>> '{0:08b}'.format(6)
'00000110'
只是解釋格式化字符串的部分:
Just to explain the parts of the formatting string:
{}
將變量放入字符串中0
獲取參數(shù)位置 0 處的變量:
為該變量添加格式選項(否則它將表示十進制6
)08
將數(shù)字格式化為 8 位數(shù)字,左側(cè)補零b
將數(shù)字轉(zhuǎn)換為二進制表示
{}
places a variable into a string0
takes the variable at argument position 0:
adds formatting options for this variable (otherwise it would represent decimal6
)08
formats the number to eight digits zero-padded on the leftb
converts the number to its binary representation
如果您使用的是 Python 3.6 或更高版本,您還可以使用 f-strings:
If you're using a version of Python 3.6 or above, you can also use f-strings:
>>> f'{6:08b}'
'00000110'
這篇關(guān)于在python中將整數(shù)轉(zhuǎn)換為二進制的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!