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

2024-09-30 14:19:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我想写一个代码,从字符串中去掉所有非字母字符。Alpha字符是a-z、a-z和0-9。所以这段代码也会删除空格,但不会在空字符串上崩溃。 例如:

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

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

有办法吗


Tags: to字符串代码alphagoreturn字母it
1条回答
网友
1楼 · 发布于 2024-09-30 14:19:50

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'

相关问题 更多 >