如何只保留字符串的字母数字字符?

2024-03-29 08:52:02 发布

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

如何在字符串中保留字母数字字符。你知道吗

正则表达式

def process_text(text):
    """
    Remove special characters
    Keep Alpha numeric + Space

    """    
    pattern = r'[^a-zA-Z0-9\s]'         
    text = re.sub(pattern,' ',text)
    text = " ".join(text.split())
    return text

示例字符串

RegExr was created by gskinner34 in the summer of 69 :-).

预期产量

RegExr was created by gskinner34 in the summer of

Tags: ofthe字符串textinby字母数字
1条回答
网友
1楼 · 发布于 2024-03-29 08:52:02

这可能有助于:

def process_text(text):
    from string import ascii_letters  as al
    return ' '.join(i for i in text.split() if any(j for j in al if j in i))
s = 'RegExr was created by gskinner34 in the summer of 69.'
print(process_text(s))

输出

'RegExr was created by gskinner34 in the summer of'

相关问题 更多 >