Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fixed width number formatting python 3

Tags:

How do I get an integer to fill 0's to a fixed width in python 3.2 using the format attribute? Example:

a = 1 print('{0:3}'.format(a)) 

gives ' 1' instead of '001' I want. In python 2.x, I know that this can be done using

print "%03d" % number.  

I checked the python 3 string documentation but wasn't able to get this.

http://docs.python.org/release/3.2/library/string.html#format-specification-mini-language

Thanks.

like image 501
pogo Avatar asked Jul 29 '11 07:07

pogo


People also ask

What does %S and %D do in Python?

They are used for formatting strings. %s acts a placeholder for a string while %d acts as a placeholder for a number.

How do you print a string at a fixed width in Python?

Show activity on this post. def splitter(str): for i in range(1, len(str)): start = str[0:i] end = str[i:] yield (start, end) for split in splitter(end): result = [start] result. extend(split) yield result el =[]; string = "abcd" for b in splitter("abcd"): el.

How do you write width in Python?

String ljust() Parametersljust() method takes two parameters: width - width of the given string. If width is less than or equal to the length of the string, the original string is returned. fillchar (Optional) - character to fill the remaining space of the width.


2 Answers

Prefix the width with a 0:

>>> '{0:03}'.format(1) '001' 

Also, you don't need the place-marker in recent versions of Python (not sure which, but at least 2.7 and 3.1):

>>> '{:03}'.format(1) '001' 
like image 128
Marcelo Cantos Avatar answered Sep 22 '22 14:09

Marcelo Cantos


Better:

number=12 print(f'number is equal to {number:03d}') 
like image 42
Mendi Barel Avatar answered Sep 20 '22 14:09

Mendi Barel