始める無料で始める

パターンで分割する

movies リストが与えられます。各要素には映画名、公開年、監督が格納されています(例: "The Godfather, 1972, Francis Ford Coppola")。

正規表現を使って分割の練習をしましょう。あなたの課題は、リストの各要素から映画名と監督名を取り出すことです。たとえば、要素が "The Godfather, 1972, Francis Ford Coppola" の場合、結果は次のようになります。

['The Godfather', 'Francis Ford Coppola']

最終的には、この結果を1つの文字列に変換します。例:

"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)
コードを編集して実行