如何将字符串解析为浮点数或整数?

2719

19
通常情况下,如果你在Python中有一个对象,并且想将其转换为该类型的对象,请对其调用 type(my_object)。结果通常可以作为函数调用来执行转换。例如,type(100) 的结果是 int,因此你可以调用 int(my_object) 来尝试将 my_object 转换为整数。这种方法并不总是可行的,但在编码时是一个好的“第一推荐”。 - robertlayton
还要确保该字符串实际上可以转换为浮点数。做到这一点的一种方法是编写一个带有try/except块的自定义函数,检查try范围内是否包含return float(str_value) - InfiniteStack
33个回答

6

处理十六进制、八进制、二进制、十进制和浮点数

此解决方案将处理数字的所有字符串约定(我所知道的全部约定)。

def to_number(n):
    ''' Convert any number representation to a number
    This covers: float, decimal, hex, and octal numbers.
    '''

    try:
        return int(str(n), 0)
    except:
        try:
            # Python 3 doesn't accept "010" as a valid octal.  You must use the
            # '0o' prefix
            return int('0o' + n, 0)
        except:
            return float(n)

这个测试案例的输出结果展示了我所说的内容。

======================== CAPTURED OUTPUT =========================
to_number(3735928559)   = 3735928559 == 3735928559
to_number("0xFEEDFACE") = 4277009102 == 4277009102
to_number("0x0")        =          0 ==          0
to_number(100)          =        100 ==        100
to_number("42")         =         42 ==         42
to_number(8)            =          8 ==          8
to_number("0o20")       =         16 ==         16
to_number("020")        =         16 ==         16
to_number(3.14)         =       3.14 ==       3.14
to_number("2.72")       =       2.72 ==       2.72
to_number("1e3")        =     1000.0 ==       1000
to_number(0.001)        =      0.001 ==      0.001
to_number("0xA")        =         10 ==         10
to_number("012")        =         10 ==         10
to_number("0o12")       =         10 ==         10
to_number("0b01010")    =         10 ==         10
to_number("10")         =         10 ==         10
to_number("10.0")       =       10.0 ==         10
to_number("1e1")        =       10.0 ==         10

以下是测试内容:

class test_to_number(unittest.TestCase):

    def test_hex(self):
        # All of the following should be converted to an integer
        #
        values = [

                 #          HEX
                 # ----------------------
                 # Input     |   Expected
                 # ----------------------
                (0xDEADBEEF  , 3735928559), # Hex
                ("0xFEEDFACE", 4277009102), # Hex
                ("0x0"       ,          0), # Hex

                 #        Decimals
                 # ----------------------
                 # Input     |   Expected
                 # ----------------------
                (100         ,        100), # Decimal
                ("42"        ,         42), # Decimal
            ]



        values += [
                 #        Octals
                 # ----------------------
                 # Input     |   Expected
                 # ----------------------
                (0o10        ,          8), # Octal
                ("0o20"      ,         16), # Octal
                ("020"       ,         16), # Octal
            ]


        values += [
                 #        Floats
                 # ----------------------
                 # Input     |   Expected
                 # ----------------------
                (3.14        ,       3.14), # Float
                ("2.72"      ,       2.72), # Float
                ("1e3"       ,       1000), # Float
                (1e-3        ,      0.001), # Float
            ]

        values += [
                 #        All ints
                 # ----------------------
                 # Input     |   Expected
                 # ----------------------
                ("0xA"       ,         10),
                ("012"       ,         10),
                ("0o12"      ,         10),
                ("0b01010"   ,         10),
                ("10"        ,         10),
                ("10.0"      ,         10),
                ("1e1"       ,         10),
            ]

        for _input, expected in values:
            value = to_number(_input)

            if isinstance(_input, str):
                cmd = 'to_number("{}")'.format(_input)
            else:
                cmd = 'to_number({})'.format(_input)

            print("{:23} = {:10} == {:10}".format(cmd, value, expected))
            self.assertEqual(value, expected)

数值错误:无法将字符串转换为浮点数。 - Avi Thour

4
a = int(float(a)) if int(float(a)) == float(a) else float(a)

3
这是Totoro's answer的修正版本。

这段代码试图解析一个字符串,并根据字符串代表的内容返回intfloat。它可能会引发解析异常或出现一些意外行为

  def get_int_or_float(v):
        number_as_float = float(v)
        number_as_int = int(number_as_float)
        return number_as_int if number_as_float == number_as_int else
        number_as_float

2

如果你需要处理混合整数和浮点数,并且想要一种处理混合数据的一致方法,那么这里是我的解决方案,附带适当的文档字符串

def parse_num(candidate):
    """Parse string to number if possible
    It work equally well with negative and positive numbers, integers and floats.

    Args:
        candidate (str): string to convert

    Returns:
        float | int | None: float or int if possible otherwise None
    """
    try:
        float_value = float(candidate)
    except ValueError:
        return None

    # Optional part if you prefer int to float when decimal part is 0
    if float_value.is_integer():
        return int(float_value)
    # end of the optional part

    return float_value

# Test
candidates = ['34.77', '-13', 'jh', '8990', '76_3234_54']
res_list = list(map(parse_num, candidates))
print('Before:')
print(candidates)
print('After:')
print(res_list)

输出:

Before:
['34.77', '-13', 'jh', '8990', '76_3234_54']

After:
[34.77, -13, None, 8990, 76323454]

1

使用:

def num(s):
    try:
        for each in s:
            yield int(each)
    except ValueError:
        yield float(each)
a = num(["123.55","345","44"])
print a.next()
print a.next()

这是我能想到的最Pythonic的方式。


1
生成器在第一次解释“float”后停止。 “try”…“catch”块可能应该在“for”循环内部。 - musiphil

1
如果您不想使用第三方模块,以下可能是最强大的解决方案:
def string_to_int_or_float(s):
    try:
        f = float(s) # replace s with str(s) if you are not sure that s is a string
    except ValueError:
        print("Provided string '" + s + "' is not interpretable as a literal number.")
        raise
    try:
        i = int(str(f).rstrip('0').rstrip('.'))
    except:
        return f
    return i

它可能不是最快的,但它正确处理了字面数字,而许多其他解决方案则失败,例如:

>>> string_to_int_or_float('789.')
789
>>> string_to_int_or_float('789.0')
789
>>> string_to_int_or_float('12.3e2')
1230
>>> string_to_int_or_float('12.3e-2')
0.123
>>> string_to_int_or_float('4560e-1')
456
>>> string_to_int_or_float('4560e-2')
45.6

0
你可以通过简单地进行以下操作来实现这一点:
s = '542.22'

f = float(s) # This converts string data to float data with a decimal point
print(f) 

i = int(f) # This converts string data to integer data by just taking the whole number part of it
print(i) 

想了解更多关于解析数据类型的信息,请查看Python文档!


0
这是一个函数,它将根据实际提供的字符串是否看起来像 int 或 float 来将任何对象(不仅仅是 str)转换为 int 或 float。此外,如果是一个既有 __float__ 和 __int__ 方法的对象,则默认使用 __float__。
def conv_to_num(x, num_type='asis'):
    '''Converts an object to a number if possible.
    num_type: int, float, 'asis'
    Defaults to floating point in case of ambiguity.
    '''
    import numbers

    is_num, is_str, is_other = [False]*3

    if isinstance(x, numbers.Number):
        is_num = True
    elif isinstance(x, str):
        is_str = True

    is_other = not any([is_num, is_str])

    if is_num:
        res = x
    elif is_str:
        is_float, is_int, is_char = [False]*3
        try:
            res = float(x)
            if '.' in x:
                is_float = True
            else:
                is_int = True
        except ValueError:
            res = x
            is_char = True

    else:
        if num_type == 'asis':
            funcs = [int, float]
        else:
            funcs = [num_type]

        for func in funcs:
            try:
                res = func(x)
                break
            except TypeError:
                continue
        else:
            res = x

0

如果您想将类型更改为其他数据类型,则可以使用显式类型转换,这意味着您必须使用 int() 将字符串类型更改为 integer,并使用 float() 将其更改为 float 类型。

但是,如果我们深入了解类型转换的概念,我们会意识到,除非必要,否则类型转换不是程序员的好选择,因此我们应该仅在需要时才使用类型转换,例如当您使用输入函数输入用户输入值时。

额外提示:您还可以使用类型转换将 tuple 转换为 list,然后将它们转换回 tuple,从而可以对不可变数据类型 tuple 进行更改(list()tuple() 是相应的函数)。


0

通过使用 int 和 float 方法,我们可以将字符串转换为整数和浮点数。

s="45.8"
print(float(s))

y='67'
print(int(y))

2
这个回答没有提供任何新的信息。例如,可以查看这个回答,它提供了相同的信息和更多内容。 - Georgy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接