格式化字串常值(f-strings)
到目前為止,我們在這堂課都使用以 "" 或 '' 包起來的一般字串。不過,Python 有多種字串形式,可以與變數混合使用。Python 最新加入的字串形式是「f-strings」,全名是格式化字串常值。f-strings 讓你能輕鬆把字串、變數與格式組合在一起,精準得到想要的輸出。用法是在引號前加上字母 f,例如 f""。如果你想把變數放進字串裡,可以在 f-string 中用 {} 包住變數名稱,這樣就會把該變數的值插入到字串本身。例如,若我們有一個變數 count,裡面存的是數字 12,就可以建立一個 f-string:f"{count} cookies",印出時會得到字串 "12 cookies"。清單 top_ten_girl_names 內含多個 tuple,每個 tuple 對應到該名次的 top_ten_rank 與 name。
本練習屬於課程
Python 的資料型別
練習說明
- 針對清單
top_ten_girl_names進行迴圈,並用 tuple 拆解取得top_ten_rank與name。 - 依序印出每個名次與名字,格式為
Rank #: 1 - Jada,其中數字 1 代表名次,Jada 代表名字。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Loop over top_ten_girl_names and unpack each tuple into top_ten_rank and name
for ____, ____ in ____:
# Print each name in the proper format
print(____"Rank #: ____ top_ten_rank ____ - { ____ }")