def get_project_name(project_string):
GG = '%.2f' % (float(re.findall(r"\d+\.?\d*", str(project_string))[0]))
print (GG)
return GG
有時候這個函數獲取的條目是空白的,這會導致「索引超出範圍錯誤」。當re.findall找不到該模式時該怎麼辦
我怎樣才能修復它忽略爲空白,則項目繼續進行下去?謝謝。
def get_project_name(project_string):
GG = '%.2f' % (float(re.findall(r"\d+\.?\d*", str(project_string))[0]))
print (GG)
return GG
有時候這個函數獲取的條目是空白的,這會導致「索引超出範圍錯誤」。當re.findall找不到該模式時該怎麼辦
我怎樣才能修復它忽略爲空白,則項目繼續進行下去?謝謝。
您可以使用try
和except
。
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"
你應該明確地捕獲一個'IndexError' –
如果你想同樣的邏輯適用於兩個「發現」和「未找到」的情況下,你也可以使用next
用默認值(分割位,使其更清晰):
p = r"\d+\.?\d*"
text = str(project_string)
GG = '%.2f' % (float(next(re.findall(p, text), 0.0)))
但是如果你只需要在第一次比賽,它實際上是更好地使用re.finditer
或re.search
,但那些返回Match
對象,而不是直接匹配的字符串。
m = re.search(p, text)
GG = '%.2f' % (float(m.group()) if m else 0.0)
在嘗試訪問其第一個元素之前,您可以檢查're.findall()'的返回值的長度。或者,你可以使用'try ... except' –
如果你只想要第一個,你爲什麼要用'findall'?使用're.search' –
我正在掃描多個Excel行以檢索一個數字。 – Allen