Python 中的 % 對字串做什麼?


% 是字串格式化運算子或插值運算子。給定格式 % 值(其中格式是一個字串),格式中的 % 轉換規範將被值的一個或多個元素替換。效果類似於在 C 語言中使用 sprintf()。例如:

>>> lang = "Python"
>>> print "%s is awesome!" % lang
Python is awesome

你還可以使用此符號格式化數字。例如:

>>> cost = 128.527
>>> print "The book costs $%.2f at the bookstore" % cost
The book costs $128.53 at the bookstore

你還可以使用字典插值字串。它們有一個語法,你需要在 % 和轉換字元之間的括號中提供鍵。例如:

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

更新於: 2019 年 9 月 30 日

214 次瀏覽

開啟您的事業

完成課程,獲得認證

開始學習
廣告
© . All rights reserved.