2016-02-04 151 views
0
def parse_distance(string): 
    # write the pattern 
    pp = re.compile("\d+") 
    result = pp.search(string) 
    if True: 
     # turn the result to an integer and return it 
     dist = int(result) 
     return dist 
    else: 
     return None 

parse_distance("LaMarcus Aldridge misses 13-foot two point shot") 

我需要從上面顯示的字符串中獲得13,它給了我錯誤,int(結果)有錯誤,不是字符串。所以我需要從字符串中獲取數字並將其轉換爲整數,我該如何去做,謝謝。我怎樣才能從給定的字符串提取數字

回答

3

您需要從group()得到匹配的數字:

def parse_distance(string): 
    pp = re.compile(r"(\d+)-foot") 
    match = pp.search(string) 
    return int(match.group(1)) if match else None 

一些用法示例:

>>> print(parse_distance("LaMarcus Aldridge misses 13-foot two point shot")) 
13 
>>> print(parse_distance("LaMarcus Aldridge misses 1300-foot two point shot")) 
1300 
>>> print(parse_distance("No digits")) 
None 
+0

即使沒有模式中的捕獲組,您也可以使用group()或group(0)來獲得全文匹配。 – Blckknght

+0

@Blckknght好點,更新。謝謝。 – alecxe

+0

非常感謝。 – user5372470

0

似乎想從給定的字符串中提取數字;

import re 

In [14]: sentence = "LaMarcus Aldridge misses 13-foot two point shot" 
In [15]: result = re.findall('\d+', sentence) 
In [16]: print result 
['13'] 
In [17]: [int(number) for number in result ] 
Out[17]: [13] 

或;

In [19]: result = [int(r) for r in re.findall('\d+', sentence)] 
In [20]: result 
Out[20]: [13] 
相關問題