python 只number類型補充(將字符串型的二進制數轉換為int類型)


我們都知道將int型轉換為字符串是:

string = str(123456)

我們還知道將一個十進制數轉換為二進制數:

num = bin(123)

我們還知道將一個二進制轉換為十進制數:

int_num = int(0b11111)

如何將一個字符串類型的十進制數轉換為二進制數呢,很簡單

先將字符串類型轉換為int型,然后在轉為二進制數不就好了嗎?

string = "123"
int_num = int(string)
bin_num = bin(int_num)

好了,大功告成!很簡單!

那么,如何將一個字符串類型的二進制數(類似於這樣的 "1111111")轉換為十進制數呢?

有人肯定是這么想的:

bin_str = "1111"
bin_num = bin(bin_str)
int_num = int(bin_num)

但是會發現報錯:

Traceback (most recent call last):
  File "G:/python作業/test-1/si1.py", line 313, in <module>
    bin_num = bin(bin_str)
TypeError: 'str' object cannot be interpreted as an integer

然而python中的int方法就可以辦到,完成轉換:

bin_str = "1111"

int_num = int(bin_str, 2)
print(int_num)

執行結果:

C:\Python36\python.exe G:/python作業/test-1/si1.py
15

Process finished with exit code 0

 

int(x=0) -> integer
        int(x, base=10) -> integer
        
        Convert a number or string to an integer, or return 0 if no arguments
        are given.  If x is a number, return x.__int__().  For floating point
        numbers, this truncates towards zero.
        
        If x is not a number or if base is given, then x must be a string,
        bytes, or bytearray instance representing an integer literal in the
        given base.  The literal can be preceded by '+' or '-' and be surrounded
        by whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.
        Base 0 means to interpret the base from the string as an integer literal.
        >>> int('0b100', base=0)
        4
        # (copied from class doc)

翻譯:

待續............

 


免責聲明!

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



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