求该段代码的作用!
如题width = int(input('Please enter width:'))
price_width = 10
item_width = width - price_width
header_fmt = '{{:{}}}{{:>{}}}'.format(item_width, price_width)
fmt = '{{:{}}}{{:>{}.2f'.format((item_width, price_width))
print('=' * width)
print(header_fmt.format('Item', 'Price'))
print('-' * width)
print(fmt.format('Apples', 0.4))
print(fmt.format('Pear', 0.5))
print(fmt.format('Cantaloupes', 1.92))
print(fmt.format('Dried Apricots (16 oz.)', 8))
print(fmt.format('Prunes (4 1bs.)', 12))
print('=' * width)
自己运行一下不就OK wp231957 发表于 2021-5-31 17:56
自己运行一下不就OK
输入格式不对,没有结果 废物弟弟云小舟 发表于 2021-6-2 01:22
输入格式不对,没有结果
你输入整数就行了。
输入大于 10 的数值就行:
width = int(input('Please enter width:'))
price_width = 10
item_width = width - price_width
header_fmt = '{{:{}}}{{:>{}}}'.format(item_width, price_width)
fmt = '{{:{}}}{{:>{}.2f}}'.format(item_width, price_width)
print('=' * width)
print(header_fmt.format('Item', 'Price'))
print('-' * width)
print(fmt.format('Apples', 0.4))
print(fmt.format('Pear', 0.5))
print(fmt.format('Cantaloupes', 1.92))
print(fmt.format('Dried Apricots (16 oz.)', 8))
print(fmt.format('Prunes (4 1bs.)', 12))
print('=' * width) 废物弟弟云小舟 发表于 2021-6-2 01:22
输入格式不对,没有结果
width = int(input('Please enter width:'))
price_width = 10
item_width = width - price_width
header_fmt = '{{:{0}}}{{:>{1}}}'.format(item_width, price_width)
fmt = '{{:{0}}}{{:>{1}.2f}}'.format(item_width, price_width)
print('=' * width)
print(header_fmt.format('Item', 'Price'))
print('-' * width)
print(fmt.format('Apples', 0.4))
print(fmt.format('Pear', 0.5))
print(fmt.format('Cantaloupes', 1.92))
print(fmt.format('Dried Apricots (16 oz.)', 8))
print(fmt.format('Prunes (4 1bs.)', 12))
print('=' * width)
'''
Please enter width:40
========================================
Item Price
----------------------------------------
Apples 0.40
Pear 0.50
Cantaloupes 1.92
Dried Apricots (16 oz.) 8.00
Prunes (4 1bs.) 12.00
========================================
''' 先去菜鸟教程看看 str.format()的基本用法,然后理解 "{{"在这里的用处,就能明白了
# "{{ " 在format中的作用
print("{{ {} }}".format("<--- 保留一个'{' --->"))
# 先取到值(可用索引),然后在冒号后设定填充格式:{索引:[填充字符][对齐方式][宽度]}
# *<20:左对齐,总共20个字符,不够的用*号填充
print('{0:*<20}'.format('hellopython'))
# *>20:右对齐,总共20个字符,不够的用*号填充
print('{0:*>20}'.format('hellopython'))
# *^20:居中显示,总共20个字符,不够的用*号填充
print('{0:*^20}'.format('hellopython'))
输出:
hellopython*********
*********hellopython
****hellopython*****
页:
[1]