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)
翻译:
待续............