最近使用python寫一腳本,就字符串中數字問題,網上查了下原來python早都為我們提供了很好的方法,在次感嘆自己python的無知,在此做下記錄
>>> crazystring = ‘dade142.;!0142f[.,]ad’
只保留數字 >>> filter(str.isdigit, crazystring) ‘1420142’
只保留字母 >>> filter(str.isalpha, crazystring) ‘dadefad’
只保留字母和數字 >>> filter(str.isalnum, crazystring) ‘dade1420142fad’
如果想保留數字0-9和小數點’.’ 則需要自定義函數
>>> filter(lambda ch: ch in ‘0123456789.’, crazystring) ‘142.0142.’
或者使用正則表達式或循環