gpt4 book ai didi

python - 从 Python 列表项中删除标点符号

转载 作者:太空狗 更新时间:2023-10-29 20:33:06 25 4
gpt4 key购买 nike

我有一个 list

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

这应该变成

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

我只想删除标点符号,保留字母和数字。标点符号是 string.punctuation 常量中的任何内容。我知道这很简单,但我对 python 有点菜鸟,所以...

谢谢,焦达米利奥

最佳答案

假设您的初始列表存储在变量 x 中,您可以这样使用:

>>> x = [''.join(c for c in s if c not in string.punctuation) for s in x]
>>> print(x)
['hello', '', 'h3a', 'ds4']

删除空字符串:

>>> x = [s for s in x if s]
>>> print(x)
['hello', 'h3a', 'ds4']

关于python - 从 Python 列表项中删除标点符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4371231/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com