作者newbrain (没有真心就别谈感情)
看板Python
标题[问题] 字串.format 花括号数量问题
时间Thu Mar 10 22:12:24 2022
抱歉我又来问了,这个问题上网查结果不知怎麽查起,
只好来ptt问看看了
我最觉得奇怪的是第四行为什麽使用的是三层花括号,而不是两重花括号
-->header_fmt = '{{:{}}}{{:>{}}}'.format(item_width, price_width)
-->header_fmt = '{{:25}}{{:>10}}'
==>print(header_fmt.format('Item', 'Price'))
-->print('{{:25}}{{:>10}}'.format('Item', 'Price')
-->print('{'Item Price'}') 最後一行
降子一来最後一行的那两个花括号不就多此一举了吗?
我的意思是一开始就只需要两层花括号不是吗?
不知道有没有大大听得懂我的问题..谢谢
# 根据指定的宽度打印格式良好的价格列表
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('Pears', 0.5))
print(fmt.format('Cantaloupes', 1.92))
print(fmt.format('Dried Apricots (16 oz.)', 8))
print(fmt.format('Prunes (4 lbs.)', 12))
print('=' * width)
这个程序的运行情况类似于下面这样:
Please enter width: 35
===================================
Item Price
-----------------------------------
Apples 0.40
Pears 0.50
Cantaloupes 1.92
Dried Apricots (16 oz.) 8.00
Prunes (4 lbs.) 12.00
===================================
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 122.116.228.113 (台湾)
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Python/M.1646921546.A.4E9.html
1F:推 lycantrope: 印出来啊, "{{:{}}}".format(5) == "{:5}" 03/10 22:40