Probably a silly question, but in python is there a simple way to automatically pad a number with zeros to a fixed length? I wasn’t able to find this in the python docs, but I may not have been looking hard enough? e.i. I want bin(4) to return 00100, rather than just 100. Is there a simple way to ensure the output will be six bits instead of three?
Share
Strings have a
.zfill()method to pad it with zeros:For binary numbers however, I’d use string formatting:
The
:05bformatting specification formats the number passed in as binary, with 5 digits, zero padded. See the Python format string syntax. I’ve usedstr.format()here, but the built-informat()function can take the same formatting instruction, minus the{0:..}placeholder syntax:if you find that easier.