【发布时间】:2022-11-22 14:43:56
【问题描述】:
我想知道如何删除一个或多个单词末尾和开头的标点符号。 如果单词之间有标点符号,我们不会删除。
例如:
输入:
word = "!.test-one,-"
输出:
word = "test-one"
【问题讨论】:
-
嘿@shrmn,到目前为止你尝试过什么来解决这个问题?
我想知道如何删除一个或多个单词末尾和开头的标点符号。 如果单词之间有标点符号,我们不会删除。
例如:
输入:
word = "!.test-one,-"
输出:
word = "test-one"
【问题讨论】:
使用strip
>>> import string
>>> word = "!.test-one,-"
>>> word.strip(string.punctuation)
'test-one'
【讨论】:
使用re.sub
import re
word = "!.test-one,-"
out = re.sub(r"(^[^w]+)|([^w]+$)", "", s)
print(out)
给#
test-one
【讨论】: