Python 的 % 對字串執行了什麼操作?


% 是一個字串格式化運算子,或插值運算子。給定格式 % 值(其中格式是一個字串),格式中的 % 轉換規範用值中的 0 個或多個元素替換。其作用類似於在 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.