python - 是否有一个函数可以从字符串中删除任何符号(%、# 等)?
问题描述
我想有效地从我的字符串中删除所有符号。
x = hello!!
r = dict.fromkeys(map(ord, '\n ' + string.punctuation))
x.translate(r)
我希望这会删除所有符号,而不仅仅是句号(。)
解决方案
如何使用re.sub
删除所有string.punctuation
和' \n'
:
x = re.sub('|'.join(map(re.escape, string.punctuation + ' \n')), '', x)
如果您只想保留字母和数字字符,也可以使用以下正则表达式:
x = re.sub('[^a-zA-Z0-9]', '', x)
推荐阅读
- c# - 从属性中获取属性的名称
- c# - DataGridViewComboBoxColumn 中的选定项目始终检索第一个值
- android - Uri 和 WebView 类以不同方式解析包含权限(主机或用户信息)中的反斜杠的 URL
- python - 如何使用python从cloudformation堆栈字典中获取特定字段的值
- php - 如何使用 Yii2 kartik-mpdf 添加水印
- c# - 有办法发送所有完整选项出现在 firebase 云消息传递创建消息页面
- php - 使用 $wpdb->prepare 查询 IN 子句
- c# - 无法访问数组中抽象类实例的字段
- xml - VB.net XML 到 DataSet - 不同 DataTables 项之间的关系
- python - 如何使用 python digi-xbee 库从本地 xbee 接收多个 ATCommand 响应数据包,用于“FN”(查找邻居)AT 命令