2017-06-19 693 views
0
def get_project_name(project_string): 
    GG = '%.2f' % (float(re.findall(r"\d+\.?\d*", str(project_string))[0])) 
    print (GG) 
    return GG 

有時候這個函數獲取的條目是空白的,這會導致「索引超出範圍錯誤」。當re.findall找不到該模式時該怎麼辦

我怎樣才能修復它忽略爲空白,則項目繼續進行下去?謝謝。

+1

在嘗試訪問其第一個元素之前,您可以檢查're.findall()'的返回值的長度。或者,你可以使用'try ... except' –

+1

如果你只想要第一個,你爲什麼要用'findall'?使用're.search' –

+0

我正在掃描多個Excel行以檢索一個數字。 – Allen

回答

2

您可以使用tryexcept

def get_project_name(project_string): 
    try: 
     GG = '%.2f' % (float(re.findall(r"\d+\.?\d*", str(project_string))[0])) 
     print GG 
     return GG 
    except Exception: 
     print "Some error message" 
+0

你應該明確地捕獲一個'IndexError' –

0

如果你想同樣的邏輯適用於兩個「發現」和「未找到」的情況下,你也可以使用next用默認值(分割位,使其更清晰):

p = r"\d+\.?\d*" 
text = str(project_string) 
GG = '%.2f' % (float(next(re.findall(p, text), 0.0))) 

但是如果你只需要在第一次比賽,它實際上是更好地使用re.finditerre.search,但那些返回Match對象,而不是直接匹配的字符串。

m = re.search(p, text) 
GG = '%.2f' % (float(m.group()) if m else 0.0)