python - 如何使用列表理解删除字符串中的标点符号?
问题描述
如何使用列表理解删除字符串中的标点符号?
punctuations="!@#$%^&*()_-=+:;{}[]<>,.?/\''"
analyzed=""
text="This is ;;;; $# @#%@$ A String <>?::"
我知道如何使用 For 循环:
for i in text:
if i not in punctuations:
analyzed+=i
print(analyzed)
但是如何使用列表理解来做到这一点?
解决方案
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 '
推荐阅读
- java - Java 8 - 使用比较器以不同的顺序比较多个字段
- html - 使 DIV 向下滚动隐藏在 body 后面
- xml - python在xtree标签名称中插入架构url
- css - 在“渲染:背景”日历上显示事件标题
- python - 如何使用 numpy 将 uint32 整数写入 4 字节序列?
- javascript - Cropper - 以多边形裁剪图像
- openlayers - 如何通过无限平移(OpenLayers)获取投影特征的坐标
- credentials - 使用本地管理员凭据在服务器之间复制项目
- javascript - Javascript Image 对象未绘制到 2D 画布
- wordpress - 从WordPress中的插件实例化一个类