如何去掉字符串中的所有空格和标点符号?(python)

如何去掉字符串中的所有空格和标点符号?(python),python,function,python-3.x,ide,Python,Function,Python 3.x,Ide,请尝试以下代码 def pre_process(t): """ (str) -> str returns a copy of the string with all punctuation removed, and all letters set to lowercase. The only characters in the output will be lowercase letters, numbers, and whitespace. """ 您应该退出

请尝试以下代码

def pre_process(t):
    """ (str) -> str
    returns a copy of the string with all punctuation removed, and all letters set to lowercase. The only characters in the output will be lowercase letters, numbers, and whitespace.

    """

您应该退出
这是一个示例语句

只需用字母数字字符重建字符串:

import re

string = 'This is an example sentence.'
string = re.sub(r'[^a-zA-Z\d]', string)

print(string)

这是使用
regex
我可以组合起来实现您的需求的最简单的函数

''.join(_char for _char in _str.lower() if _char.isalnum())

它将以小写形式返回输入字符串,并省略任何非字母、数字或空格的字符。

您尝试了什么?你用谷歌搜索了吗?如果你愿意,你会得到第一个链接的答案检查结果你试过我的答案了吗?关于“123!@Test”呢?观察得很好!我也把数字放进去了,我想这就是OP想要的。谢谢!很好用!
import re
def pre_process(t):
    return re.sub(r'[^a-z\d ]','',str.lower())