上QQ阅读APP看书,第一时间看更新
How to do it...
- Write the following script, recipe_format_strings_step1.py, to print an aligned table:
# INPUT DATA
data = [
(1000, 10),
(2000, 17),
(2500, 170),
(2500, -170),
]
# Print the header for reference
print('REVENUE | PROFIT | PERCENT')
# This template aligns and displays the data in the proper format
TEMPLATE = '{revenue:>7,} | {profit:>+7} | {percent:>7.2%}'
# Print the data rows
for revenue, profit in data:
row = TEMPLATE.format(revenue=revenue, profit=profit, percent=profit / revenue)
print(row)
- Run it to display the following aligned table. Note that PERCENT is correctly displayed as a percentage:
REVENUE | PROFIT | PERCENT
1,000 | +10 | 1.00%
2,000 | +17 | 0.85%
2,500 | +170 | 6.80%
2,500 | -170 | -6.80%