2016-09-28 185 views
2

我有以下字符串數值,並且只需要保留數字和小數。我無法爲此找到正確的正則表達式。Python - 將字符串 - 數字轉換爲浮點數

s = [ 
     "12.45-280", # need to convert to 12.45280 
     "A10.4B2", # need to convert to 10.42 
] 
+1

那麼你的第一個預期輸出值是浮點數-267.55還是字符串「12.45-280」? –

+1

你試過了什麼正則表達式,他們給了什麼結果? – CAB

+0

試過'[0-9 \。]。??? – alvas

回答

0

轉換每個字母字符的字符串空字符「」

import re 
num_string = []* len(s) 
for i, string in enumerate(s): 
    num_string[i] = re.sub('[a-zA-Z]+', '', string) 
0

你可以去爲locale組合和正則表達式:

import re, locale 
from locale import atof 

# or whatever else 
locale.setlocale(locale.LC_NUMERIC, 'en_GB.UTF-8') 

s = [ 
     "12.45-280", # need to convert to 12.45280 
     "A10.4B2", # need to convert to 10.42 
] 

rx = re.compile(r'[A-Z-]+') 

def convert(item): 
    """ 
    Try to convert the item to a float 
    """ 
    try: 
     return atof(rx.sub('', item)) 
    except: 
     return None 

converted = [match 
      for item in s 
      for match in [convert(item)] 
      if match] 

print(converted) 
# [12.4528, 10.42] 
1

您還可以刪除所有非數字和非圓點字符,然後將結果轉換爲浮點數:

In [1]: import re 
In [2]: s = [ 
    ...:  "12.45-280", # need to convert to 12.45280 
    ...:  "A10.4B2", # need to convert to 10.42 
    ...: ] 

In [3]: for item in s: 
    ...:  print(float(re.sub(r"[^0-9.]", "", item))) 
    ...:  
12.4528 
10.42 

這裏[^0-9.]可以匹配除數字或文字點以外的任何字符。

+0

一個數字中只能有一個點。負號的負號也應該被接受。 – VPfB

+0

@ VPfB可能需要考慮的好點,謝謝 – alecxe

相關問題