2016-11-26 58 views
0

例如,如果我有以下字符串:如何從字符串中提取以特定字母/字符開頭的子字符串?

fruits = "The apples are $3.00, the oranges are $2.00, and the grapes are $10000." 

我想提取的價格像這樣的列表:

['$3.00', '$2.00', '$10000'] 

到目前爲止,我已經做到了這一點:

def extract_prices(s): 
    prices = [] 
    for i in range(len(s)): 
     if s[i] == '$': 
     prices.append(s[i], s.find(' ')) 

我覺得最後一行是給我的問題。我不知道如何獲得價格之後的空間索引,以及如何在該空間停止索引。

任何提示?感謝您閱讀本文!對不起,如果我的解釋不清楚。

+0

看看正則表達式https://docs.python.org/3 /library/re.html模塊 – pythad

+0

對不起,這會有幫助嗎?這有點長,我不知道從哪裏開始:o謝謝你的回覆! – Katerina

+0

正則表達式對於字符串解析非常有用。考慮看看他們的教程 – qxz

回答

3

分割字符串,並尋找美元符號:

>>> fruits = "The apples are $3.00, the oranges are $2.00, and the grapes are $10000." 
>>> result = [item.strip(',.!?') for item in fruits.split() if '$' in item] 
>>> result 
['$3.00', '$2.00', '$10000'] 

記住,從每個項目剝離標點符號。

4

您可以使用正則表達式:

>>> fruits = "The apples are $3.00, the oranges are $2.00, and the grapes are $10000." 
>>> re.findall(r'(\$[\d.]+)', fruits) 
['$3.00', '$2.00', '$10000.'] 

或者,如果你想更具體的,只包括.如果有數字:

>>> re.findall(r'(\$\d+(?:\.\d+)?)', fruits) 
['$3.00', '$2.00', '$10000'] 
+2

請注意,最後一個元素有一個無關的句點。 – TigerhawkT3

+0

可能是無關的或模糊的! – dawg

+1

如果是......而葡萄是$ 10000.00,那怎麼辦?「'? – TigerhawkT3

0

使用下面的正則表達式:

re.findall('\$\d+\.?\d+', fruits) 

輸出:

>>> re.findall('\$\d+\.?\d+', fruits) 
['$3.00', '$2.00', '$10000'] 
+2

請注意,由於'.'的原因,它也會匹配'$ 10/1'等東西。 – TigerhawkT3

+0

@ TigerhawkT3編輯,謝謝:) – ettanany

0

如果只想調整原代碼,使用

if s[i] == '$': 
    lastPos = s.find(',', i) 
    if lastPos == -1: 
     lastPos = len(s) 
    prices.append(s[i:lastPos]) 

你的線條,而不是

if s[i] == '$': 
    prices.append(s[i], s.find(' ')) 
相關問題