Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add leading zeroes to a string Python [duplicate]

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:

         val.appendleft("0")

By the way, deque is a type of object from collections that allows you to leftappend 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.

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. Sorry about the dupe.

LAST EDIT I SWEAR: I just noticed something. I keep getting values like 000b0110 when trying to make it one-byte long. This is opposed to 00000110 that I wanted. I'm just adding this so that if anyone else in the future looks up this question they'll find the correct thing. So all I've done is ignore the first two character of the string by using:

val = val[2::].rjust(8, '0')

I'm getting this because I'm turning a number INTO a binary number with "bin" which returns a string that has the "0b" (declaring it as binary) at the beginning.

like image 867
Frogboxe Avatar asked Sep 29 '16 18:09

Frogboxe


People also ask

How do you add leading zeros to a string in Python?

For padding a string with leading zeros, we use the zfill() method, which adds 0's at the starting point of the string to extend the size of the string to the preferred size. In short, we use the left padding method, which takes the string size as an argument and displays the string with the padded output.

How do you add leading zeros to a string?

The format() method of String class in Java 5 is the first choice. You just need to add "%03d" to add 3 leading zeros in an Integer. Formatting instruction to String starts with "%" and 0 is the character which is used in padding. By default left padding is used, 3 is the size and d is used to print integers.

How can I pad a value with leading zeros?

To pad an integer with leading zeros to a specific length To display the integer as a decimal value, call its ToString(String) method, and pass the string "Dn" as the value of the format parameter, where n represents the minimum length of the string.

What does 0 2f mean in Python?

>>> "Floating point {0:.2f}". format(345.7916732) Here we specify 2 digits of precision and f is used to represent floating point number. Expected Output: Floating point 345.79.


2 Answers

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.

like image 179
Martijn Pieters Avatar answered Nov 14 '22 21:11

Martijn Pieters


You can use the formatting language but this particular example is probably unnecessary:

>>> format('101', '<08')
'10100000'
>>> "{:<0{width}}".format('101', width=8)
'10100000'
like image 32
AChampion Avatar answered Nov 14 '22 22:11

AChampion