Python - 将字符串数字转换为float

时间:2016-09-28 17:36:43

标签: python regex typeconverter

我有以下字符串数值,并且只需要保留数字和小数。我无法为此找到正确的正则表达式。

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

3 个答案:

答案 0 :(得分: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.]将匹配除数字或字面点之外的任何字符。

答案 1 :(得分:0)

将字符串中的每个字母字符转换为空字符“”

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

答案 2 :(得分: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]
相关问题