Python 的 bin(~)
方法將整數轉換為前綴為 “0b”
的二進製字符串。如果提供的輸入不是整數,則必須實現 __index__()
方法來返回整數。
參數
1. x
| integer
要轉換為二進製字符串的整數。
返回值
以 "0b"
為前綴的整數的轉換後的二進製字符串。
例子
基本用法
要返回 6
的二進製字符串:
bin(6)
'0b110'
請注意,"0b"
僅表示它是一個二進製字符串。
__index__()方法
要將 bin(~)
方法與實現 __index__()
方法的輸入結合使用:
class score:
james = 2
sally = 4
tom = 3
def __index__(self):
return self.james + self.sally + self.tom
bin(score())
'0b1001'
我們提供 score
類的實例作為 bin(~)
方法的輸入。盡管實例本身不是整數,但由於它返回一個整數(james + sally + tom
的總和),在本例中為 9
,因此 bin(~)
返回 9
的二進製字符串。
TypeError
如果我們提供整數以外的輸入:
bin('Hi')
TypeError: 'str' object cannot be interpreted as an integer
相關用法
- Python binascii.crc32用法及代碼示例
- Python binary轉string用法及代碼示例
- Python binary轉ASCII用法及代碼示例
- Python NumPy bincount方法用法及代碼示例
- Python bin用法及代碼示例
- Python binascii.b2a_hex用法及代碼示例
- Python bin()用法及代碼示例
- Python NumPy busdaycalendar對象用法及代碼示例
- Python bytes.isupper用法及代碼示例
- Python base64.b64decode()用法及代碼示例
- Python bokeh.plotting.figure.asterisk()用法及代碼示例
- Python bytes.zfill用法及代碼示例
- Python base64.b32decode()用法及代碼示例
- Python bytes.expandtabs用法及代碼示例
- Python bytearray()用法及代碼示例
- Python bokeh.plotting.figure.annular_wedge()用法及代碼示例
- Python NumPy base屬性用法及代碼示例
- Python Pandas bdate_range方法用法及代碼示例
- Python bytes.isalpha用法及代碼示例
- Python base64.b85encode()用法及代碼示例
- Python base64.b64encode()用法及代碼示例
- Python bokeh.plotting.figure.circle()用法及代碼示例
- Python bytes.hex用法及代碼示例
- Python bool()用法及代碼示例
- Python bz2.decompress(s)用法及代碼示例
注:本文由純淨天空篩選整理自Arthur Yanagisawa大神的英文原創作品 Python | bin method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。