Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I format a number with a variable number of digits in Python?

Say I wanted to display the number 123 with a variable number of padded zeroes on the front.

For example, if I wanted to display it in 5 digits I would have digits = 5 giving me:

00123 

If I wanted to display it in 6 digits I would have digits = 6 giving:

000123 

How would I do this in Python?

like image 897
Eddy Avatar asked Jul 12 '10 13:07

Eddy


People also ask

Can you format a variable Python?

Python uses C-style string formatting to create new, formatted strings. The "%" operator is used to format a set of variables enclosed in a "tuple" (a fixed size list), together with a format string, which contains normal text together with "argument specifiers", special symbols like "%s" and "%d".

How do you format a number in Python?

When formatting the floating point number 123.4567 , we've specified the format specifier ^-09.3f . These are: ^ - It is the center alignment option that aligns the output string to the center of the remaining space. - - It is the sign option that forces only negative numbers to show the sign.

What does {: 2f mean in Python?

A format of . 2f (note the f ) means to display the number with two digits after the decimal point. So the number 1 would display as 1.00 and the number 1.5555 would display as 1.56 .

How do I fix the number of digits in Python?

We can also use the round() function to fix the numbers of digits after the decimal point. This function limits the number of digits after the decimal point on the input number. It also rounds off the digit at which limit is set to its upper integral value if the digit is greater than value 5 .


2 Answers

If you are using it in a formatted string with the format() method which is preferred over the older style ''% formatting

>>> 'One hundred and twenty three with three leading zeros {0:06}.'.format(123) 'One hundred and twenty three with three leading zeros 000123.' 

See
http://docs.python.org/library/stdtypes.html#str.format
http://docs.python.org/library/string.html#formatstrings

Here is an example with variable width

>>> '{num:0{width}}'.format(num=123, width=6) '000123' 

You can even specify the fill char as a variable

>>> '{num:{fill}{width}}'.format(num=123, fill='0', width=6) '000123' 
like image 71
John La Rooy Avatar answered Oct 04 '22 20:10

John La Rooy


There is a string method called zfill:

>>> '12344'.zfill(10) 0000012344 

It will pad the left side of the string with zeros to make the string length N (10 in this case).

like image 24
Donald Miner Avatar answered Oct 04 '22 21:10

Donald Miner