किसी पैटर्न के आधार पर splitting
आपको movies नाम की list दी गई है, जहाँ हर एलिमेंट में एक मूवी का नाम, उसकी रिलीज़ डेट, और डायरेक्टर स्टोर होता है (उदाहरण: "The Godfather, 1972, Francis Ford Coppola").
आइए रेगुलर एक्सप्रेशन की मदद से कुछ splitting का अभ्यास करें। आपका काम list के हर एलिमेंट से उसका नाम और डायरेक्टर निकालना है। उदाहरण के लिए, अगर एलिमेंट "The Godfather, 1972, Francis Ford Coppola" है, तो परिणाम होगा:
['The Godfather', 'Francis Ford Coppola']
अंत में, इस परिणाम को एक single string में बदलना है, जैसे
"The Godfather, Francis Ford Coppola"
यह अभ्यास पाठ्यक्रम का हिस्सा है
Python में कोडिंग इंटरव्यू प्रश्नों का अभ्यास
अभ्यास निर्देश
- ऐसा रेगुलर एक्सप्रेशन compile करें जो
moviesकी strings को मूवी नाम और उसके डायरेक्टर में split करे. re.split()का उपयोग करके मूवी नाम और डायरेक्टर प्राप्त करें.- मूवी नाम और डायरेक्टर को
,से अलग करते हुए एक नई string बनाएँ. - बनी हुई string को
movies_without_yearमें append करें.
इंटरैक्टिव व्यावहारिक अभ्यास
इस अभ्यास को इस नमूना कोड को पूरा करके आज़माएँ।
# 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)