Frogboxe Frogboxe - 3 months ago 11
Python Question

Add leading zeroes to a string Python

So I've got an algorithm that does this already, but the code is ugly and slow. I assume that there's a built-in or some function in the libs that give faster and more precise results.

What I want it where I can give a final number of bits, a string, list or deque (anything that can be cast to a string in the end).

func(totalBits, binaryInStringOrListForm) -> String or List with leading zeroes

The code I've already got is below:

val = deque(["1", "0"])

while len(val) < 8:


By the way, deque is a type of object from collections that allows you to
wherein you can add an item to the beginning of the list without having to shift everything over by one.

There are old answers to this but they're all Python 2 and the whole formatting thing has changed significantly.

Thank you for your time.

EDIT: I think that this question is not a duplicate of the one linked as I was actually after leading zeroes as @Martijn Pieters has made me aware.

EDIT: Ok, it IS a duplicate of that one it seems. Thank you anyhow. Sorry about the dupe.


There is a built-in, the str.ljust() method. It takes the target width and an optional fill character (defaulting to a space). You can use it to pad out a string with '0' characters:

val = val.ljust(8, '0')

There is also an equivalent str.rjust() method to add padding on the left.

However, if you want leading zeros (as opposed to trailing), I'd use the str.zfill() method as that takes any - or + prefix into account.