What is the easiest way to pad a string with 0 to the left so that
"110" = "00000110"
"11110000" = "11110000"
I have tried to use the format!
macro but it only pads to the right with space:
format!("{:08}", string);
leftPad() method to left pad a string with zeros, by adding leading zeros to 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.
Python String zfill() MethodThe zfill() method adds zeros (0) at the beginning of the string, until it reaches the specified length. If the value of the len parameter is less than the length of the string, no filling is done.
The standard way to add padding to a string in Python is using the str. rjust() function. It takes the width and padding to be used. If no padding is specified, the default padding of ASCII space is used.
The fmt
module documentation describes all the formatting options:
Fill / Alignment
The fill character is provided normally in conjunction with the
width
parameter. This indicates that if the value being formatted is smaller thanwidth
some extra characters will be printed around it. The extra characters are specified byfill
, and the alignment can be one of the following options:
<
- the argument is left-aligned inwidth
columns^
- the argument is center-aligned inwidth
columns>
- the argument is right-aligned inwidth
columns
assert_eq!("00000110", format!("{:0>8}", "110")); // ||| // ||+-- width // |+--- align // +---- fill
See also:
As an alternative to Shepmaster's answer, if you are actually starting with a number rather than a string, and you want to display it as binary, the way to format that is:
let n: u32 = 0b11110000; // 0 indicates pad with zeros // 8 is the target width // b indicates to format as binary let formatted = format!("{:08b}", n);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With