【问题标题】:How to remove symbols from a string with Python? [duplicate]如何使用 Python 从字符串中删除符号? [复制]
【发布时间】:2010-10-26 22:24:05
【问题描述】:

我是 Python 和 RegEx 的初学者,我想知道如何制作一个包含符号并用空格替换它们的字符串。任何帮助都很棒。

例如:

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

进入:

how much for the maple syrup 20 99 That s ridiculous

【问题讨论】:

  • 我的建议是阅读re 库的文档。它包括一些很好的例子。
  • 奇怪的是,这被标记为与一年后提出的问题的重复。

标签: python regex string


【解决方案1】:

一种方式,使用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] 将匹配任何字母数字或下划线

【讨论】:

  • 需要注意的是,括号外的 ^\w 表示“匹配行首的字母数字字符”。插入符号仅在括号( [^\w] )内表示“忽略此处的每个字符”
  • @cmptrgeekken:谢谢,已修复。
  • 你也可以使用 \W 来代替 [^\w],它与 \w 正好相反。
  • 感染 [/\W+/g] 会变魔术。
  • 这是否适用于包含“é”字符的字符串。输出是保留还是删除这个字符?
【解决方案2】:

有时找出正则表达式比在 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)

【讨论】:

  • 我刚刚在我正在做的一个项目中使用了这种白名单方法。谢谢!
  • +1,pythonic,喜欢它。
【解决方案3】:

我经常只是打开控制台并在对象方法中寻找解决方案。很多时候它已经存在了:

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

简答:使用string.replace()

【讨论】:

  • 我认为这个答案是不完整的看问题
猜你喜欢
  • 2020-10-17
  • 1970-01-01
  • 1970-01-01
  • 2014-01-26
  • 2022-01-15
  • 1970-01-01
  • 2019-07-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多