从 python 中删除第一个和最后一个标点符号

Removing first and last punctuation from python

我有以下问题,我想去掉开头和结尾的标点符号,但保留中间的标点符号。
例子。 \

[':Hamburger{', 'word>', 'don´t', 'isn´t,'] 

这应该会变成

['Hamburger', 'word', 'don´t', 'isn´t']

所以如果有人能帮助我,我将不胜感激

您可以为此使用正则表达式。只需 import re 在文件的开头,然后您可以使用以下行来替换所有标点符号以及行的开头或结尾:

for el in list:
    el = re.sub("^[^\w\s]|[^\w\s]$", "", el)

string模块有一个预定义的常用标点符号字符串:

>>> from string import punctuation as punct
>>> punct
'!"#$%&\'()*+,-./:;<=>?@[\]^_`{|}~'

您可以将其与 str.strip 结合使用以去除每个字符串:

>>> "<>.,.,.!TEST<>>..]}".strip(punct)
'TEST'

def make_pretty(word):
    from string import punctuation as punct
    return word.strip(punct)

words = [':Hamburger{', 'word>', 'don´t', 'isn´t,']

print(list(map(make_pretty, words)))

输出:

['Hamburger', 'word', 'don´t', 'isn´t']

话虽这么说,string.punctuation 并不详尽。例如,字符 ´ 不存在,因此不会被删除。