如何用Python删除字符串中的符号?

aar*_*ont 69 python regex string

我是Python和RegEx的初学者,我想知道如何创建一个带符号的字符串并用空格替换它们.任何帮助都很棒.

例如:

how much for the maple syrup? $20.99? That's ricidulous!!!
Run Code Online (Sandbox Code Playgroud)

成:

how much for the maple syrup 20 99 That s ridiculous
Run Code Online (Sandbox Code Playgroud)

dF.*_*dF. 123

一种方法,使用正则表达式:

>>> s = "how much for the maple syrup? $20.99? That's ridiculous!!!"
>>> re.sub(r'[^\w]', ' ', s)
'how much for the maple syrup   20 99  That s ridiculous   '
Run Code Online (Sandbox Code Playgroud)
  • \w 将匹配字母数字字符和下划线

  • [^\w]将匹配任何不是字母数字或下划线的东西

  • 应该注意,括号外的^\w表示"在一行的开头匹配一个字母数字字符".它只在括号([^\w])内,插入符号表示"忽略此处的每个字符" (14认同)
  • 代替[^\w]你也可以使用\ W,这与\ w相反. (10认同)

mon*_*kut 27

有时需要更长的时间来计算出正则表达式而不是在python中写出来:

import string
s = "how much for the maple syrup? $20.99? That's ricidulous!!!"
for char in string.punctuation:
    s = s.replace(char, ' ')
Run Code Online (Sandbox Code Playgroud)

如果您需要其他字符,可以将其更改为使用白名单或扩展黑名单.

样本白名单:

whitelist = string.letters + string.digits + ' '
new_s = ''
for char in s:
    if char in whitelist:
        new_s += char
    else:
        new_s += ' '
Run Code Online (Sandbox Code Playgroud)

使用generator-expression示例白名单:

whitelist = string.letters + string.digits + ' '
new_s = ''.join(c for c in s if c in whitelist)
Run Code Online (Sandbox Code Playgroud)

  • 我刚刚将这个白名单方法用于我正在进行的项目.谢谢! (2认同)

bus*_*ter 8

我经常只是打开控制台,然后在对象方法中寻找解决方案。通常已经存在:

>>> a = "hello ' s"
>>> dir(a)
[ (....) 'partition', 'replace' (....)]
>>> a.replace("'", " ")
'hello   s'
Run Code Online (Sandbox Code Playgroud)

简短答案:使用string.replace()