2015-10-06 73 views
1

當我運行下面的代碼。如何從分割函數中獲取值?

x="abc=2015 and xyz=1806".split("=") 
print x 

我得到這個:

['abc', '2015 and xyz', '1806'] 

但是,我想輸出20151806

任何人都可以幫助我。

+0

...然後根據需要索引到列表中 – jonrsharpe

+1

'print x [4:8],x [17:22]'給你你想要的東西。 – Psytho

+0

@ Alex.S雖然這是一個有點脆弱 – jonrsharpe

回答

0
x="abc=2015 and xyz=1806" 
print [i.split("=")[1] for i in x.split() if '=' in i] 

輸出:['2015', '1806']

你可以先分割,然後檢查是否=存在,然後通過=分裂。

1
import re 
print(' '.join(re.split('\D',"abc=2015 and xyz=1806"))) 

2015   1806 

或列表:

print([int(x) for x in re.split('\D',"abc=2015 and xyz=1806") if x.isdigit()]) 

[2015, 1806] 
+0

如果你打算使用're',爲什麼不只是're.findall(r'\ d +','abc = 2015和xyz = 1806')'? – jonrsharpe

+0

@jonrsharpe OP想拆......我已經證明了他分裂的另一種方式...... – LetzerWille

0
string = "abc=2015 and xyz=1806" 
x = [int(i.split("=")[1]) for i in string.split() if '=' in i] 
print(x) 
+1

雖然這個答案可能是正確的,請加一些解釋。賦予基礎邏輯比賦予代碼更重要,因爲它可以幫助OP和其他讀者自己解決這個問題和類似的問題。 – CodeMouse92

1

無需加盟,或分割,如果它是一個選項。

>>> x="abc=2015 and xyz=1806" 
>>> import re 
>>> y = re.findall('\d+', x) 
>>> print(y) 
['2015', '1806'] 
0
import re 

s='abc = 2015 and xyz = 1806' 
r='[=\s*](\d+)' 
for x in re.findall(r, s): 
    print(x) 
+0

雖然這個答案可能是正確的,但請添加一些解釋。賦予基礎邏輯比賦予代碼更重要,因爲它可以幫助OP和其他讀者自己解決這個問題和類似的問題。 – CodeMouse92

1

好很多的選擇,這裏是另一種,如果你知道" and "是分離,那麼你可以拆分在" and "第一:

>>> x="abc=2015 and xyz=1806" 
>>> [s.split('=')[1] for s in x.split(" and ")] 
['2015', '1806'] 

或者在一個字典保持標籤值一起並只打印這些值:

>>> d = dict(s.split('=') for s in x.split(" and ")) 
>>> d.values() 
['1806', '2015']