開始使用免費開始

在字串中尋找其他字串

在處理字串時,我們常常會在意其中包含哪些字元。舉例來說,你可能想知道在一份 cookie 名稱清單裡,有多少項包含 Chocolate 這個字,或有多少是以字母 C 開頭。你可以在字串上使用 in 關鍵字與 .startswith() 方法來完成這些檢查。我們也可以在串列生成式中加入條件,格式為 [action for item in list if something is true]。以剛剛的 cookie 例子來說,會像是 [cookie_name for cookie_name in cookies if 'chocolate' in cookie_name.lower()]。注意這些檢查會區分大小寫,所以我們在字串上使用 .lower() 方法。此外,我們也可以「串接」方法,將多個方法連著呼叫。

本練習屬於課程

Python 的資料型別

檢視課程

練習說明

  • 儲存並印出一個以 s 開頭的 girl_names 串列。
  • 儲存並印出一個包含 angelgirl_names 串列。

動手互動練習

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

# Store a list of girl_names that start with s: names_with_s
names_with_s = [____ for name in girl_names if ____.lower().____('____')]

print(names_with_s)

# Store a list of girl_names that contain angel: names_with_angel
names_with_angel = [name for name in ____ if '____' in name.____()]

print(names_with_angel)
編輯並執行程式碼