如何使用 Python 3 中的字典來格式化字串?


你可以使用字典來插值字串。它們有一個語法,你需要在 % 和轉換字元之間的括號中提供 key。例如,如果你有一個儲存在 key 'cost' 中的 float 值並且想將其格式化為 '$xxxx.xx',那麼你將在想顯示它的位置放置 '$%(cost).2f'。

以下是使用字串格式化在字典中插值字串和格式化數字的示例

>>>print('%(language)s has %(number)03d quote types.' % {'language': "Python", "number": 2})
Python has 002 quote types.

你可以在此處閱讀有關字串格式化及其運算子的更多資訊:https://docs.python.club.tw/3/library/stdtypes.html#printf-style-string-formatting

更新於:13-Jun-2020

628 次瀏覽

開啟你的 職業生涯

完成教程後獲得認證

開始學習
廣告