依模式分割
給你一個 movies 清單,其中每個元素都包含片名、上映年份與導演(例如:"The Godfather, 1972, Francis Ford Coppola")。
讓我們用正規表示式來練習分割。你的任務是從清單中的每個元素擷取片名與導演。例如,若元素是 "The Godfather, 1972, Francis Ford Coppola",結果應為:
['The Godfather', 'Francis Ford Coppola']
最後,請把這個結果改成單一字串,例如:
"The Godfather, Francis Ford Coppola"
本練習屬於課程
Python 程式面試題實作練習
練習說明
- 編譯一個正規表示式,將
movies中的字串分割為片名與導演。 - 使用
re.split()擷取片名與導演。 - 建立一個新字串,片名與導演以
,分隔。 - 將產生的字串加入
movies_without_year。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Compile a regular expression
pattern = re.compile(____)
movies_without_year = []
for movie in movies:
# Retrieve a movie name and its director
split_result = re.split(____)
# Create a new string with a movie name and its director
movie_and_director = ', '.____
# Append the resulting string to movies_without_year
movies_without_year.____
for movie in movies_without_year:
print(movie)