python - 在 pyton 中使用正则表达式在字符串中只保留字母和数字
问题描述
我有字符串,例如:'1212kk,l' 使用正则表达式,我必须删除除数字和字母之外的所有内容并得到:'1212kkl'
解决方案
如果是字母或数字,请使用str.isalnum()
which chekcs:
text = "1212kk , l"
# Option 1:
# The `x for x in text` goes on string characters
# The `if x.isalnum()` filters in only letters and digits
# The `''.join()` takes the filtered list and joins it to a string
filtered = ''.join([x for x in text if x.isalnum()])
# Option 2:
# Applay `filter` of `text` characters that `str.isalnum` returns `True` for them
# The `''.join()` takes the filtered list and joins it to a string
filtered = ''.join(filter(str.isalnum, text))
# 1212kkl
print(filtered )
推荐阅读
- email - Microsoft Graph - 仅获取最新消息内容
- php - Add class to div when woocommerce cart is empty
- jenkins - 新的 jenkins 从节点何时以及如何有资格在其上执行作业?
- javascript - 当标签处于活动状态或不在 React Native 中时更改标签栏图标
- python - 熊猫:如何生成新列以获取另一列的最后日期时间值
- javascript - 有没有办法使用空手道 DSL 获得 sessionStorage?
- xml - Powershell - XML - 如何从每个节点系列的不同深度提取多个值
- linux - 在周日某个时间之后和周五某个时间之前运行 cron 的干净方式
- excel - VBA使用文件中的参数列表查找/替换并在搜索字符串中包含空格
- c++ - std::function 模板参数推导