python-23-零基础自学python open()和replace()函数运用

学习内容:《python编程:从入门到实践》第二版练习10-2

知识点:

打开文件,replace()替换文件内容,open(),

练习内容:

练习10-2:C语言学习笔记 可使用方法replace()将字符串中的特定单词都替换为另一个单词。读取你刚创建的文件learning_python.txt中的每一行,将其中的Python都替换为另一门语言的名称,比如C。将修改后的各行都打印到屏幕上。

我的代码&运行结果:

python 复制代码
filename = '10_learning_python.txt'

with open(filename) as file_object:
    lines = file_object.readlines()

for line in lines:
    line = line.replace('Python','C')
    print(line)

总结&问题:

1.代码中line = line.replace('Python','C')不能只写 line.replace('Python','C'),会不显示替换后的内容,不像函数方法的调用,不需要加上=的内容。

2.替换的过程有点像excel的ctrl+f/G,选择替换后就全部换掉了。

相关推荐
Flittly8 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(3)TodoWrite (待办写入)
python·agent
千寻girling12 小时前
一份不可多得的 《 Django 》 零基础入门教程
后端·python·面试
databook16 小时前
探索视觉的边界:用 Manim 重现有趣的知觉错觉
python·动效
明月_清风17 小时前
Python 性能微观世界:列表推导式 vs for 循环
后端·python
明月_清风17 小时前
Python 性能翻身仗:从 O(n) 到 O(1) 的工程实践
后端·python
helloweilei1 天前
python 抽象基类
python
用户8356290780511 天前
Python 实现 PPT 转 HTML
后端·python
zone77392 天前
004:RAG 入门-LangChain读取PDF
后端·python·面试
zone77392 天前
005:RAG 入门-LangChain读取表格数据
后端·python·agent
树獭非懒2 天前
AI大模型小白手册|Embedding 与向量数据库
后端·python·llm