開始使用免費開始

尋找子字串

新的一天開始,你需要繼續為電影預測專案清理資料集。探索資料時,你注意到一個奇怪的模式:在第 37 個字元到第 41 個字元之間,出現一些重複且連續的單字。你決定寫一個函式找出哪些影評有這個特徵,並記得你指定的結束位置是不包含在內的。如果偵測到該單字,你也想把它替換為只出現一次的形式。

請依照指示完成 if-else 敘述。

三條影評文字已經儲存在變數 movies 中。你可以在 IPython Shell 中使用 print(movies) 檢視變數內容。

本練習屬於課程

Python 中的正規表示法

檢視課程

練習說明

  • 檢查子字串 actor 是否出現在索引為 3741(含)的字元之間。若未偵測到,請列印 Word not found
  • 如果 actor 僅連續出現兩次,將 actor actor 取代為子字串 actor
  • 如果 actor 連續出現三次,將 actor actor actor 取代為子字串 actor

動手互動練習

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

for movie in movies:
  	# If actor is not found between character 37 and 41 inclusive
    # Print word not found
    if movie.find("____", ____, ____) == ____:
        print("Word not found")
    # Count occurrences and replace two with one
    elif movie.____("____") == 2:  
        print(movie.replace("____", "____"))
    else:
        # Replace three occurrences with one
        print(movie.replace("____", "____"))
編輯並執行程式碼