Python學習筆記之replace()


10-2 可使用方法replace()將字符串中的特定單詞都替換為另一個單詞。

讀取你剛創建的文件learning_python.txt 中的每一行,將其中的Python 都替換為另一門語言的名稱,如C。將修改后的各行都打印到屏幕上。

learning_python.txt文件內容如下:

1 In Python you can Handle file
2 In Python you can Automatic operation and maintenance
3 In Python you can make AI

 

編寫Python代碼:

1 filename='learning_python.txt'
2 with open(filename) as file_object:
3     lines = file_object.readlines()
4     for line in lines:
5         print(line.replace('Python', 'C'))

 

執行結果:

1 In C you can Handle file
2 
3 In C you can Automatic operation and maintenance
4 
5 In C you can make AI

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM