【问题标题】:Python - remove punctuation marks at the end and at the beginning of one or more wordsPython - 删除一个或多个单词末尾和开头的标点符号
【发布时间】:2022-11-22 14:43:56
【问题描述】:

我想知道如何删除一个或多个单词末尾和开头的标点符号。 如果单词之间有标点符号,我们不会删除。

例如: 输入: word = "!.test-one,-" 输出: word = "test-one"

【问题讨论】:

标签: python algorithm


【解决方案1】:

使用strip

>>> import string
>>> word = "!.test-one,-"
>>> word.strip(string.punctuation)
'test-one'

【讨论】:

    【解决方案2】:

    使用re.sub

    import re
    word = "!.test-one,-"
    out = re.sub(r"(^[^w]+)|([^w]+$)", "", s)
    print(out)
    

    给#

    test-one
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-03
      • 1970-01-01
      • 2023-01-31
      相关资源
      最近更新 更多