[問題] 字串.format 花括號數量問題
抱歉我又來問了,這個問題上網查結果不知怎麼查起,
只好來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://www.ptt.cc/bbs/Python/M.1646921546.A.4E9.html
推
03/10 22:40,
2年前
, 1F
03/10 22:40, 1F
討論串 (同標題文章)
以下文章回應了本文:
完整討論串 (本文為第 1 之 2 篇):