第1单 1.4创建带格式的字符串
使用template.format(*parameters)函数创建带格式的字符串。
代码如下:
#!/usr/bin/env python
data = [
(1000, 10),
(2000, 17),
(2500, 170),
(2500, -170),
]
# Print the header for reference
print('REVENUE | PROFIT | PERCENT')
#以下是格式模板
TEMPLATE = '{revenue:>7,} | {profit:>+7} | {percent:>7.2%}'
# 显示数据
for revenue, profit in data:
percent = profit / revenue
row = TEMPLATE.format(revenue=revenue, profit=profit, percent=percent)
print(row)
其中"{revenue:>7,}"中的'>'为右对齐,7指数据宽度为7,而','是指使用','作为千位分隔符;"{profit:>+7}"中的'+'是指数据为正值时自动添加'+',为负值时自动添加'-'号;"{percent:>7.2%}"中的'.2'指保留两位小数,'%'指以百分比显示。

浙公网安备 33010602011771号