要分割多行,還是分割單行?
你正要下班時,有位同事請你幫忙運用字串處理技巧。你需要從檔案讀取字串;若檔案內容分成不同的行,就要把它們各自存成獨立的元素。他也希望你在看到逗號時,把字串再切成多個片段。
檔案的文字內容已儲存在變數 file 中。你可以在 IPython Shell 中使用 print(file) 檢視這個變數。
本練習屬於課程
Python 中的正規表示法
練習說明
- 在行邊界將字串
file分割成多個子字串。 - 列印變數
file_split的結果。 - 完成 for 迴圈,使用逗號作為分隔符,將字串再分割成多個子字串。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Split string at line boundaries
file_split = ____
# Print file_split
print(____)
# Complete for-loop to split by commas
for ____ in ____:
substring_split = substring.____
print(substring_split)