Re: [問題] 字串.format 花括號數量問題

看板Python作者 (大歐派蘿莉)時間2年前 (2022/03/10 22:42), 2年前編輯推噓1(100)
留言1則, 1人參與, 2年前最新討論串2/2 (看更多)
※ 引述《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://www.ptt.cc/bbs/Python/M.1646923345.A.07F.html ※ 編輯: DaOppaiLoli (58.114.11.77 臺灣), 03/10/2022 22:43:43

03/11 20:00, 2年前 , 1F
感謝
03/11 20:00, 1F
文章代碼(AID): #1YAWvH1_ (Python)
文章代碼(AID): #1YAWvH1_ (Python)