Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python integer formatting

I was wondering if it's possible to use two format options together when formatting integers.

I know I can use the bellow to include zero places

varInt = 12

print(
    "Integer : " +
    "{:03d}".format(varInt)
)

To get the output "Integer : 012"

I can use the following to include decimal places

varInt = 12

print(
    "Integer : " +
    "{:.3f}".format(varInt)
)

To get the output "Integer : 12.000"

But is it possible to use them both together to get the output "Integer : 012.000"

like image 641
TheLovelySausage Avatar asked Aug 14 '15 15:08

TheLovelySausage


People also ask

How do I format an int in Python?

To convert a string to integer in Python, use the int() function. This function takes two parameters: the initial string and the optional base to represent the data. Use the syntax print(int("STR")) to return the str as an int , or integer.

What is %s and %D in Python?

%s is used as a placeholder for string values you want to inject into a formatted string. %d is used as a placeholder for numeric or decimal values.

What does %d do Python?

What does %d do in Python? The %d operator is used as a placeholder to specify integer values, decimals, or numbers. It allows us to print numbers within strings or other values. The %d operator is put where the integer is to be specified.

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 . A program can also specify a field width character: x = 0.1.


1 Answers

Not only can you specify the minimum length and decimal points like this:

"{:07.3f}".format(12)

You can even supply them as parameters like this:

"{:0{}.{}f}".format(12, 7, 3)
like image 125
John La Rooy Avatar answered Oct 20 '22 01:10

John La Rooy