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

2024-05-11 03:28:38 发布

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

我是一个同时使用Python和RegEx的初学者,我想知道如何创建一个字符串,它接受符号并用空格替换它们。任何帮助都很好。

例如:

how much for the maple syrup? $20.99? That's ricidulous!!!

进入:

how much for the maple syrup 20 99 That s ridiculous

Tags: the字符串forthat符号regexhow空格
3条回答

有时计算regex比用python编写要花更长的时间:

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

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

白名单示例:

whitelist = string.letters + string.digits + ' '
new_s = ''
for char in s:
    if char in whitelist:
        new_s += char
    else:
        new_s += ' '

使用生成器表达式的白名单示例:

whitelist = string.letters + string.digits + ' '
new_s = ''.join(c for c in s if c in whitelist)

我经常打开控制台,在objects方法中寻找解决方案。它经常已经在那里了:

>>> a = "hello ' s"
>>> dir(a)
[ (....) 'partition', 'replace' (....)]
>>> a.replace("'", " ")
'hello   s'

简而言之:使用string.replace()

单向,使用regular expressions

>>> 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   '
  • \w将匹配字母数字字符和下划线

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

相关问题 更多 >