繁体   English   中英

从 Python 中的字符串中去除非字母字符的代码

[英]Code to strip non-alpha characters from string in Python

我想编写一个从字符串中取出所有非字母字符的代码。 字母字符是 az、AZ 和 0-9。 因此,此代码还将删除空格,但不会在空字符串上崩溃。 例如:

to_alphanum('Cats go meow')
#it would return:
'Catsgomeow'

to_alphanum('')
#it would return:
''

有没有办法做到这一点?

strisalnum方法来检查字母数字,利用:

In [115]: def to_alphanum(text): 
     ...:     return ''.join([char for char in text if char.isalnum()]) 
     ...:                                                                                                                                                                                                   

In [116]: to_alphanum('Cats go meow')                                                                                                                                                                       
Out[116]: 'Catsgomeow'

In [117]: to_alphanum('#$')                                                                                                                                                                                 
Out[117]: ''

In [118]: to_alphanum('190 $%6')                                                                                                                                                                            
Out[118]: '1906'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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