【问题标题】:how to take away all the spaces and punctuation in a string? (python) [duplicate]如何去掉字符串中的所有空格和标点符号? (蟒蛇)[重复]
【发布时间】:2017-03-01 18:37:43
【问题描述】:
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.

    """

【问题讨论】:

  • 你试过什么?你用谷歌搜索过吗?如果你愿意,你会得到第一个链接的答案
  • 查看Google Search结果
  • 你试过我的答案了吗?

标签: python function python-3.x ide


【解决方案1】:

试试下面的代码。

import re

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

print(string)

你应该离开Thisisanexamplesentance

【讨论】:

  • “123 !@ 测试”怎么样?
  • 观察得很好!我也在那里输入了数字,我认为这就是 OP 想要的。
【解决方案2】:

这是使用regex 的最简单的功能,我可以组合起来满足您的要求。

import re
def pre_process(t):
    return re.sub(r'[^a-z\d ]','',str.lower())

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

【讨论】:

  • 谢谢!完美运行!
【解决方案3】:

只用字母数字字符重建你的字符串:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-12
    • 2011-08-16
    • 1970-01-01
    • 2017-12-28
    • 2019-08-25
    • 1970-01-01
    • 2011-05-11
    • 2020-01-09
    相关资源
    最近更新 更多