Anonypy Anonypy - 4 years ago 77
Python Question

Formatting with floats

The code below isn't complete, but should give an idea of what I'm doing. What's irritating is that my table isn't lining up after '100.001'. I want to keep the same numbers, so is there something I can do to stop the '|' from sticking out after 100.001?

for j in numbers:
print('{} {} {} {}\n'.format(number, "|", num, "|", etc, etc))



#output

1 | 0.617 | 98.333 | 98.332 | 0.108 | 0.101 | 91.678 |

2 | 0.617 | 98.332 | 98.332 | 0.101 | 0.101 | 100.001 |

3 | 0.617 | 0.180 | 98.335 | 0.106 | 98.335 | 93.330 |

4 | 0.617 | 0.107 | 98.336 | 0.105 | 0.101 | 95.004 |

Answer Source

So you want format the output numbers. To do this you can use the formatting specifiers (similar to C the printf|sprintf|fprintf functions formatting specifiers).

Firstly, you should be specific about the format of the numbers, and then, all your output will be printed on that specific format. So if you want align '100.001', I suggest you to use the format DDD.ddd (three digits numbers with three decimals). In Python use the specifier ":06.3" like the following:

'{:06.3f}'.format(3.141592653589793)

Should print:

003.142

Take a look at the complete ref here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download