Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/282.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用re.sub替换多个字符_Python_Regex_String_Python 2.7 - Fatal编程技术网

Python 使用re.sub替换多个字符

Python 使用re.sub替换多个字符,python,regex,string,python-2.7,Python,Regex,String,Python 2.7,我需要去掉s中的以下字符 s = "Bob hit a ball!, the hit BALL flew far after it was hit." 如何使用re.sub实现这一点 !?',;. 有人能告诉我这有什么问题吗?不需要正则表达式,你可以用简单的str.replace()来完成,类似这样的: re.sub(r"!|\?|'|,|;|."," ",s) #doesn't work. And replaces all characters with space 不需要正则表达式,你

我需要去掉s中的以下字符

s = "Bob hit a ball!, the hit BALL flew far after it was hit."
如何使用re.sub实现这一点

!?',;.

有人能告诉我这有什么问题吗?

不需要正则表达式,你可以用简单的str.replace()来完成,类似这样的:

re.sub(r"!|\?|'|,|;|."," ",s) #doesn't work. And replaces all characters with space

不需要正则表达式,你可以用简单的str.replace()来实现,类似这样:

re.sub(r"!|\?|'|,|;|."," ",s) #doesn't work. And replaces all characters with space

问题是
匹配所有字符,而不是文本
。你也要逃避它,
\。

但更好的方法是不使用OR运算符
|
,而只使用字符组:

chars_to_replace = "!?',;."

def replace(text):
    for char in chars_to_replace:
        if char in text:
            text = text.replace(char, "")

    return text


my_text = "Bob hit a ball!, the hit BALL flew far after it was hit."


print replace(my_text)

// Bob hit a ball the hit BALL flew far after it was hit

问题是
匹配所有字符,而不是文本
。你也要逃避它,
\。

但更好的方法是不使用OR运算符
|
,而只使用字符组:

chars_to_replace = "!?',;."

def replace(text):
    for char in chars_to_replace:
        if char in text:
            text = text.replace(char, "")

    return text


my_text = "Bob hit a ball!, the hit BALL flew far after it was hit."


print replace(my_text)

// Bob hit a ball the hit BALL flew far after it was hit

我忘了。是一个匹配所有字符的。谢谢,我在“.”中添加了一个后缺,效果很好now@Wkhan请考虑使用我提供的第二个选项,它更可读,效率更高(只有60个步骤,而不是338个步骤!)参见Re.Sub(R)!是一个匹配所有字符的。谢谢,我在“.”中添加了一个后缺,效果很好now@Wkhan请考虑使用我提供的第二个选项,它更可读,效率更高(只有60个步骤与338个步骤)!你真的在使用Python 2吗?这能回答你的问题吗?你真的在使用Python2吗?这能回答你的问题吗?