2014-02-10 77 views
-3

我有一個 'NoneType' 的物體,像選擇數字:的Python:從NoneType對象

A='ABC:123' 

我想獲得一個對象只保留位數:

A2=digitsof(A)='123' 
+9

這不是一個NoneType,這是一個字符串。你到目前爲止嘗試了什麼? – RemcoGerlich

+3

不,你做**不**有'NoneType'對象;你有一個字符串。 –

+3

如果有非連續的數字會發生什麼? ''ABC:123:456''? –

回答

1

正則表達式?

>>> from re import sub 
>>> A = 'ABC:123' 
>>> sub(r'\D', '', A) 
123 
+0

**注意:**對問題本身的所有評論都非常正確。這是一個'字符串',而不是'NoneType' – Michael

4

拆分在冒號:

>>> A='ABC:123' 
>>> numA = int(A.split(':')[1]) 
123 
1

如何:

>>> import re 
>>> def digitsof(a): 
...  return [int(x) for x in re.findall('\d+', a) ] 
... 
>>> digitsof('ABC:123') 
[123] 
>>> digitsof('ABC:123,123') 
[123, 123] 
>>> 
0

一個簡單的過濾功能

A='ABC:123'  
filter(lambda s: s.isdigit(), A) 
+1

你正在得到ABC,將它改爲isdigit() –

+0

你沒錯,編輯我的答案:) – user2814648

相關問題