我很新的python。我有個問題。例如,當我從文件中讀取一行時,我有一個看起來像這樣的字符串。如何從字符串中刪除所有非整數? (Python)
thestring = '000,5\r\n'
如何從此字符串中刪除所有非整數,然後將此字符串轉換爲整數本身?謝謝!
我很新的python。我有個問題。例如,當我從文件中讀取一行時,我有一個看起來像這樣的字符串。如何從字符串中刪除所有非整數? (Python)
thestring = '000,5\r\n'
如何從此字符串中刪除所有非整數,然後將此字符串轉換爲整數本身?謝謝!
使用str.translate
,這可能是這樣做的最快方法:
>>> strs = '000,5\r\n'
>>> from string import ascii_letters, punctuation, whitespace
>>> ignore = ascii_letters + punctuation + whitespace
>>> strs.translate(None, ignore)
'0005'
使用regex
:
>>> import re
>>> re.sub(r'[^\d]+','',strs) #or re.sub(r'[^0-9]+','',strs)
'0005'
使用str.join
和str.isdigit
:
>>> "".join([x for x in strs if x.isdigit()])
'0005'
使用int()
得到整數:
>>> int('0005')
5
時機比較:
>>> strs = strs*10**4
>>> %timeit strs.translate(None, ignore)
1000 loops, best of 3: 441 us per loop
>>> %timeit re.sub(r'[^\d]+','',strs)
10 loops, best of 3: 20.3 ms per loop
>>> %timeit re.sub(r'[^0-9]+','',strs)
100 loops, best of 3: 17.1 ms per loop
>>> %timeit "".join([x for x in strs if x.isdigit()])
10 loops, best of 3: 19.2 ms per loop
或翻譯,如果你需要更快的東西。 – placeybordeaux
@ PeterMichealLacey-Bordeaux解決方案已更新。 –
非常感謝!現在假設我的字符串是'0005'如何反轉我的字符串以使其現在讀取'5000'? – Binka
你需要能夠讀取底片,十六進制('0xFFFFFF'),或浮點數('-592.45821543e + 04' )? – AJMansfield
只是挑剔,但你不想刪除_non-integers_,但_non-digits_ –