从中的字符串读取数字

2024-09-30 03:24:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要把一些字符串转换成float。它们大多数只是数字,但也有一些有字母。函数的作用是:抛出一个错误。你知道吗

a='56.78'
b='56.78 ab'

float(a) >> 56.78
float(b) >> ValueError: invalid literal for float()

一种解决方案是检查是否存在除数字以外的其他字符,但我想知道是否有一些内置的或其他简短的函数提供:

magicfloat(a) >> 56.78
magicfloat(b) >> 56.78

Tags: 函数字符串forab错误字母数字解决方案
3条回答

使用regex

import re

def magicfloat(input):
    numbers = re.findall(r"[-+]?[0-9]*\.?[0-9]+", input)

    # TODO: Decide what to do if you got more then one number in your string
    if numbers:
        return float(numbers[0])

    return None

a=magicfloat('56.78')
b=magicfloat('56.78 ab')

print a
print b

输出:

56.78
56.78

您可以尝试从输入中删除字母:

from string import ascii_lowercase

b='56.78 ab'
float(b.strip(ascii_lowercase))

简短回答:否

没有任何内置函数可以实现这一点。你知道吗

回答:是:

您可以做的一件事是遍历字符串中的每个字符,检查它是数字还是句点,然后从那里开始使用:

def magicfloat(var):
    temp = list(var)
    temp = [char for char in temp if char.isdigit() or char == '.']
    var = "".join(temp)
    return var

因此:

>>> magicfloat('56.78 ab')
'56.78'
>>> magicfloat('56.78')
'56.78'
>>> magicfloat('56.78ashdusaid')
'56.78'
>>> 

相关问题 更多 >

    热门问题