Liz - 2 months ago 10

Python Question

I am trying to print something:

`>>> print "%02i,%02i,%02g" % (3, 4, 5.66)`

03,04,5.66

However this is not correct. If you notice, the zeroes get correctly pre-pended

to all the integer floating points (the first two numbers). I need it such that there will be one leading zero if the there is a single digit to the left of the decimal point.

I.e. the solution above should return:

`03,04,05.66`

What am I doing wrong?

Answer

For `g`

, specify and width and precision:

```
>>> print "%02i,%02i,%05.3g" % (3, 4, 5.66)
03,04,05.66
```

The difference between `f`

and `g`

is illustrated here:

```
>>> print "%07.1f, %07.1f, %07.1f" % (1.23, 4567.8, 9012345678.2)
00001.2, 04567.8, 9012345678.2
>>> print "%07.1g, %07.1g, %07.1g" % (1.23, 4567.8, 9012345678.2)
0000001, 005e+03, 009e+09
```

When given large numbers, `g`

switches to scientific notation while `f`

just uses more spaces.

Similarly, `g`

switches to scientific notation, when needed, for small numbers:

```
>>> print "%07.1f, %07.1f, %07.1f" % (.01, .0001, .000001)
00000.0, 00000.0, 00000.0
>>> print "%07.1g, %07.1g, %07.1g" % (.01, .0001, .000001)
0000.01, 00.0001, 001e-06
```

Source (Stackoverflow)

Comments