作者DaOppaiLoli (大欧派萝莉)
看板Python
标题Re: [问题] 字串.format 花括号数量问题
时间Thu Mar 10 22:42:23 2022
※ 引述《newbrain (没有真心就别谈感情)》之铭言:
: 抱歉我又来问了,这个问题上网查结果不知怎麽查起,
: 只好来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
: ===================================
第三层 Brace 是用来 Escape 第二层 Brace 用的
如果原字串想要单纯输出花括号而不是要做 Format 用途
就会用两层花括号来代表
'{{}}'.format(10) # Result: '{}'
header_fmt 是为了制造下一个 Format Syntax 所以才把第二层 Escape 掉
'{{:{}}}'.format(10) # Result: '{:10}'
'{:10}'.format('Item') # Result: 'Item '
如果没有第三层花括号,就要一次传两个参数进去
'{:{}}'.format(10) # IndexError: ...
'{:{}}'.format('Item', 10) # Result: 'Item '
希望这样有解答你心中的疑惑
参考来源:官方文件
https://docs.python.org/3.11/library/string.html#format-string-syntax
> If you need to include a brace character in the literal text, it can be
> escaped by doubling: {{ and }}.
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 58.114.11.77 (台湾)
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Python/M.1646923345.A.07F.html
※ 编辑: DaOppaiLoli (58.114.11.77 台湾), 03/10/2022 22:43:43
1F:推 newbrain: 感谢 03/11 20:00