简体   繁体   中英

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  |

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

can you try .ljust(10) to get tabular structure.

value = 100.001
number = 3.3457
num = 10.2
etc = 34.1234
for i in range(10):
  print('{} | {} | {} | {}\n'.format(str(value).ljust(10), i, etc, etc))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM