循环删除一些字符串

2024-10-01 04:49:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图删除一些字符在我的字符串,但我有一个错误,我有tride不同的方式循环,但它仍然不起作用

我的问题是如何在字符串上循环并删除字符?在

这是我的代码:

MyList= [",", ":", "\"", "=", "&", ";", "%", "$","@", "%", "^",
         "*", "(", ")", "{", "}","[", "]", "|", "/", "\\", ">",
         "<", "-",'!', '?', '.', "'",'--', '---', "#"]

for remove in MyList:   

        mystring =re.sub(remove, "", "I am trying this code")
        print (remove)

我有个错误:

^{pr2}$

抱歉我的新手问题


Tags: 字符串代码inrefor错误方式this
3条回答

已经发布了一些解决方法,但是还没有人解释这个错误。文件re.sub公司()说:

re.sub(pattern, repl, string, ...) - Return the string obtained by replacing ... pattern in string by the replacement repl

在我的列表中重复了一些符号之后,我们得到了:

re.sub("*", "", "I am trying this code")

因此,您试图将*替换为""-但是*是正则表达式中使用的“特殊”字符,在本例中,"*"是非法/无效的正则表达式。*是regex中的一个量词,意思是“返回尽可能多的重复上一个regex”——但是这个字符串中没有previous regex。在

"*"通常与"."一起使用,就像在".*"中一样,这意味着尽可能多次匹配任何单个字符(".")。在

更新:下面是如何从字符串中删除符号:

^{pr2}$

如果您的目标只是从字符串中删除所有标点符号,那么一个保留所有其他字符(_)和空格的正则表达式将是:

import re

s = "Hello, world! how are you?"

print(re.sub("[^ \w]","",s))

结果:

^{pr2}$

它比循环中的x replace调用(创建尽可能多的字符串)或正则表达式中的|更有效。在

你不需要正则表达式。只需使用str.replace

>>> MyList= [",", ":", "\"", "=", "&", ";", "%", "$","@", "%", "^",
...          "*", "(", ")", "{", "}","[", "]", "|", "/", "\\", ">",
...          "<", "-",'!', '?', '.', "'",'--', '---', "#"]
>>> mystring = "Helo, world!?"
>>> for s in MyList:
...     mystring = mystring.replace(s, '')
...
>>> mystring
'Helo world'

相关问题 更多 >