開始使用免費開始

結合多個字串

f-string 對少量變數很好用,但如果你想把整個變數串列合併成一個字串呢?你可以使用 "".join() 方法。把你想用來連接串列項目的字串放在 "" 裡,然後把串列傳入 join() 方法。例如,如果你想用逗號加空白連接名為 cookies 的串列中所有項目,可以寫成 ", ".join(cookies)

在這個練習中,你會運用這些技巧,把前 10 個男孩名字的串列轉成一句話,並存成字串。

本練習屬於課程

Python 的資料型別

檢視課程

練習說明

  • 建立一個包含:The top ten boy names are: 的字串,並儲存為 preamble
  • 建立一個包含:, and 的字串,並儲存為 conjunction
  • 建立一個把 boy_names 串列中前 9 個名字用逗號連接的字串,並儲存為 first_nine_names
  • 建立一個 f-string,內容包含 preamblefirst_nine_namesconjunctionboy_names 的最後一個項目,以及句號。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# The top ten boy names are:  as preamble
____ = "The top ten boy names are: "

# , and as conjunction
conjunction = ____

# Combines the first 9 names in boy_names with a comma and space as first_nine_names
first_nine_names = "____".join(boy_names[____:____])

# Print f-string preamble, first_nine_names, conjunction, the final item in boy_names and a period
print(f"{____}{first_nine_names}{conjunction} {____[-1]}.")
編輯並執行程式碼