【问题标题】:Removing punctuation from only the beginning and end of each element in a list in python仅从python列表中每个元素的开头和结尾删除标点符号
【发布时间】:2020-11-09 20:16:51
【问题描述】:

我对 python(和这个社区)相当陌生,这是一个从很久以前here 提出和回答的问题分支出来的问题

列表如下:

['hello', '...', 'h3.a', 'ds4,']

创建一个没有标点符号的新列表 x(并删除空元素)将是:

x = [''.join(c for c in s if c not in string.punctuation) for s in x]
x = [s for s in x if s]
print(x)

输出:

['hello', 'h3a', 'ds4']

但是,我如何才能仅从每个元素的开头和结尾删除所有标点符号?我的意思是,改为输出:

['hello', 'h3.a', 'ds4']

在这种情况下,保留 h3a 中的句点,但删除 ds4 末尾的逗号。

【问题讨论】:

  • s.strip(string.punctuation) 将是一个起点。

标签: python list punctuation


【解决方案1】:

你可以使用正则表达式。 re.sub() 可以用字符串替换正则表达式的所有匹配项。

import re
X = ['hello', '.abcd.efg.', 'h3.a', 'ds4,']
X_rep = [re.sub(r"(^[^\w]+)|([^\w]+$)", "", x) for x in X] 
print(X_rep)
# Output: ['hello', 'abcd.efg', 'h3.a', 'ds4']

正则表达式解释:Try it

  • (^[^\w]+):
    • ^: 字符串开头
    • [^\w]+:一个或多个非单词字符
  • |: 上一个表达式,或者下一个表达式
  • ([^\w]+$):
    • [^\w]+:一个或多个非单词字符
    • $: 字符串结束

【讨论】:

    【解决方案2】:
    x = ['hello', '...', 'h3.a', 'ds4,']
    x[0] = [''.join(c for c in s if c not in string.punctuation) for s in x][0]
    x[(len(x)-1)] = [''.join(c for c in s if c not in string.punctuation) for s in x][(len(x)-1)]
    x = [s for s in x if s]
    print(x)
    

    【讨论】:

    • 请参阅this 获取格式化帮助。也请使用tour 并阅读How to Answer。虽然仅代码的答案可能会回答问题,但您可以通过为代码提供上下文、此代码有效的原因以及对文档的一些参考以供进一步阅读,从而显着提高答案的质量。来自How to Answer“简洁是可以接受的,但更全面的解释更好。”欢迎来到 Stack Overflow!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-27
    • 2020-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-22
    • 1970-01-01
    相关资源
    最近更新 更多