[英]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:
''
有沒有辦法做到這一點?
str
有isalnum
方法來檢查字母數字,利用:
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.