a = "1010" # type str b = int(a,2)
print('{0:b}'.format(3))
附上关于python中format的用法:
https://www.cnblogs.com/lovejh/p/9201219.html
bin(x) 將一个整数x转换为二进制的字符串表示,转换后的是一个字符串,开头的"0b"表示是二进制。
bin(1) = '0b1' bin(2) = '0b10' bin(3) = '0b11' bin(4) = '0b100' bin(5) = '0b101'
补零思想
class Solution: def addBinary(self, a: str, b: str) -> str: r, p = '', 0 d = len(b) - len(a) a = '0' * d + a b = '0' * -d + b for i, j in zip(a[::-1], b[::-1]): s = int(i) + int(j) + p r = str(s % 2) + r p = s // 2 return '1' + r if p else r