我试图删除一些字符在我的字符串,但我有一个错误,我有tride不同的方式循环,但它仍然不起作用
我的问题是如何在字符串上循环并删除字符?在
这是我的代码:
MyList= [",", ":", "\"", "=", "&", ";", "%", "$","@", "%", "^",
"*", "(", ")", "{", "}","[", "]", "|", "/", "\\", ">",
"<", "-",'!', '?', '.', "'",'--', '---', "#"]
for remove in MyList:
mystring =re.sub(remove, "", "I am trying this code")
print (remove)
我有个错误:
^{pr2}$抱歉我的新手问题
已经发布了一些解决方法,但是还没有人解释这个错误。文件re.sub公司()说:
re.sub(pattern, repl, string, ...) - Return the string obtained by replacing ... pattern in string by the replacement repl
在我的列表中重复了一些符号之后,我们得到了:
因此,您试图将
*
替换为""
-但是*
是正则表达式中使用的“特殊”字符,在本例中,"*"
是非法/无效的正则表达式。*
是regex中的一个量词,意思是“返回尽可能多的重复上一个regex”——但是这个字符串中没有previous regex。在"*"
通常与"."
一起使用,就像在".*"
中一样,这意味着尽可能多次匹配任何单个字符("."
)。在更新:下面是如何从字符串中删除符号:
^{pr2}$如果您的目标只是从字符串中删除所有标点符号,那么一个保留所有其他字符(
_
)和空格的正则表达式将是:结果:
^{pr2}$它比循环中的x replace调用(创建尽可能多的字符串)或正则表达式中的
|
更有效。在你不需要正则表达式。只需使用
str.replace
:相关问题 更多 >
编程相关推荐