2016-09-28 21 views
2

私は以下の文字列の数値を持ち、桁と小数点のみを保持する必要があります。私はちょうどこれのための正しい正規表現を見つけることができません。Python - 文字列の数値を浮動小数点に変換する

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

最初の予想出力値はfloat -267.55か文字列 "12.45-280"ですか? –

+1

正規表現を試してみましたが、どのような結果が出ましたか? – CAB

+0

'[0-9 \。]。?'を試しましたか? – alvas

答えて

0

あなたがlocaleと正規表現の組み合わせのために行くことができ

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

「に」char空にするために、文字列内の各アルファベット文字を変換します

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

あなたはまた、すべてを削除することができます非数字、非ドット文字を入力し、結果をfloatに変換します。

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

数字には1つのドットしか使用できません。また、負の数の先頭にマイナス記号を付けることもできます。 – VPfB

+0

@VPfB考慮する必要があるかもしれない良い点、ありがとう – alecxe