简体   繁体   中英

Leave only letters and numbers in the string using a regex, in pyton

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

Use the str.isalnum() which chekcs if its either letter or digit:

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM