首页 > 解决方案 > 在 pyton 中使用正则表达式在字符串中只保留字母和数字

问题描述

我有字符串,例如:'1212kk,l' 使用正则表达式,我必须删除除数字和字母之外的所有内容并得到:'1212kkl'

标签: pythonpython-3.xregex

解决方案


如果是字母或数字,请使用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 )

推荐阅读