Python搜索和替换不起作用

Python搜索和替换不起作用,python,string,replace,Python,String,Replace,我有以下简单的HTML文件 <html data-noop=="http://www.w3.org/1999/xhtml"> <head> <title>Hello World</title> </head> <body> SUMMARY1 hello world </body> </html> 上述代码在文件中读入变量htmltemplate。 接下来,我调用string对象的replace()函

我有以下简单的
HTML
文件

<html data-noop=="http://www.w3.org/1999/xhtml">
<head>
<title>Hello World</title>
</head>
<body>
SUMMARY1
hello world
</body>
</html>
上述代码在文件中读入变量
htmltemplate
。 接下来,我调用string对象的
replace()
函数,将模式SUMMARY1替换为“hi there”。但输出似乎并没有搜索SUMMARY1并将其替换为“hi there”。这是我得到的

<html data-noop=="http://www.w3.org/1999/xhtml"><head><title>Hello World</title></head><body>SUMMARY1hello world</body></html>
Hello WorldSUMMARY1hello world
有人能指出我做错了什么吗?

open()
不返回
str
,它返回
文件
对象。此外,您打开它只是为了阅读(
'r'
),而不是为了写作

您想做的是:

new_lines = []
with open('test.html', 'r') as f:
    new_lines = f.readlines()
with open('test.html', 'w') as f:
    f.writelines([x.replace('a', 'b') for x in new_lines])

fileinput
库使这变得容易多了。

因为
open()
不返回字符串对象,而是返回文件对象。此外,您仅打开文件进行读取(
'r'
)。这也是一个重复:我想我犯的错误是在第3行。我把它改成了
htmltemplate=htmltemplate.replace('SUMMARY1','hi there')
,效果很好。你还添加了
.read()
,这是你原来的帖子中没有的,而且变化很大。但不管怎样,您仍然没有实际编辑该文件,
'SUMMARY'
仍将出现在
test.html
中。
new_lines = []
with open('test.html', 'r') as f:
    new_lines = f.readlines()
with open('test.html', 'w') as f:
    f.writelines([x.replace('a', 'b') for x in new_lines])