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

 

    原文作者:雨夜Rainight
    原文地址: https://www.cnblogs.com/rainights/p/11757436.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞