2016-09-28 149 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

相关问题