首页 > 解决方案 > 如何使用列表理解删除字符串中的标点符号?

问题描述

如何使用列表理解删除字符串中的标点符号?

punctuations="!@#$%^&*()_-=+:;{}[]<>,.?/\''"
analyzed=""
text="This is ;;;; $# @#%@$ A String <>?::"

我知道如何使用 For 循环:

for i in text:
     if i not in punctuations:
          analyzed+=i
print(analyzed)

但是如何使用列表理解来做到这一点?

标签: pythonarrayslistlist-comprehension

解决方案


punctuations="!@#$%^&*()_-=+:;{}[]<>,.?/\''"
analyzed=""
text="This is ;;;; $# @#%@$ A String <>?::"

试试这个

>>[c for c in text if c not in punctuations]

你会得到:

['T', 'h', 'i', 's', ' ', 'i', 's', ' ', ' ', ' ', ' ', 'A', ' ', 'S', 't', 'r', 'i', 'n', 'g', ' ']

如果您想将其作为单个字符串,只需将它们全部连接起来。

>>''.join(c for c in text if c not in punctuations)
'This is    A String '

推荐阅读