Python入门习题大全——索引
可使用方法replace()将字符串中的特定单词都替换为另一个单词。下面是一个简单的示例,演示了如何将句子中的’dog’替换为’cat’ :
>>> message = "I really like dogs. ”
>>> message.replace('dog', 'cat' )
'I really like cats.
读取你刚创建的文件learning_python.txt 中的每一行,将其中的Python都替换为另一门语言的名称,如C。将修改后的各行都打印到屏幕上。
# C 语言学习笔记
filename = 'learning_python.txt'
with open(filename) as file_object:
for line in file_object:
# line.replace('Python', 'C')
print(line.replace('Python', 'C').rstrip())
文件内容为:
In Python I can use any kind of num
In Python I can use letter with any operation
In Python I can use list, tuple, dictionary, for, while
In Python I can use function, class, file
输出为:
In C I can use any kind of num
In C I can use letter with any operation
In C I can use list, tuple, dictionary, for, while
In C I can use function, class, file