如何将str转换为float?"545.2222" → 545.2222如何将str转换为int?"31" → 31


相反,请参见在Python中将整数转换为字符串和将浮点转换为字符串而不舍入。

请改为使用“如何将输入读取为数字?”?关闭重复问题,其中OP从用户输入中接收到字符串并立即想要转换它,或者希望输入(在3.x中)自动转换类型。


当前回答

你可以简单地通过

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文档!

其他回答

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

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

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)

如果您正在处理混合整数和浮点数,并希望以一致的方式处理混合数据,下面是我使用正确的docstring的解决方案:

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]

这是对你的问题的另一种解释(提示:它很模糊)。你可能正在寻找这样的东西:

def parseIntOrFloat( aString ):
    return eval( aString )

它是这样工作的。。。

>>> parseIntOrFloat("545.2222")
545.22220000000004
>>> parseIntOrFloat("545")
545

理论上,存在注入漏洞。例如,字符串可以是“import os;os.art()”。然而,如果没有任何关于字符串来源的背景信息,理论上可能是推测。因为这个问题很模糊,所以根本不清楚这个漏洞是否真的存在。

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

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

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

在Python中,如何将“545.2222”这样的数字字符串解析为其对应的浮点值542.2222?或者将字符串“31”解析为整数31?我只想知道如何将浮点字符串解析为浮点,并(分别)将int字符串解析为int。

你要求单独做这些很好。如果你把它们混合在一起,你可能会为以后的问题做准备。简单的答案是:

“545.2222”浮动:

>>> float("545.2222")
545.2222

“31”转换为整数:

>>> int("31")
31

其他转换,字符串和文字之间的int:

不同基数的转换,你应该提前知道基数(默认值为10)。请注意,您可以使用Python对其文本所期望的前缀(见下文)或删除前缀:

>>> int("0b11111", 2)
31
>>> int("11111", 2)
31
>>> int('0o37', 8)
31
>>> int('37', 8)
31
>>> int('0x1f', 16)
31
>>> int('1f', 16)
31

如果您事先不知道基数,但您知道它们将具有正确的前缀,那么如果您将0作为基数传递,Python可以为您推断出这一点:

>>> int("0b11111", 0)
31
>>> int('0o37', 0)
31
>>> int('0x1f', 0)
31

其他基数的非十进制(即整数)文字

然而,如果您的动机是让自己的代码清楚地表示硬编码的特定值,那么您可能不需要从基转换-您可以让Python使用正确的语法自动为您进行转换。

您可以使用apropos前缀自动转换为具有以下文字的整数。这些对Python 2和3有效:

二进制,前缀0b

>>> 0b11111
31

八进制,前缀0o

>>> 0o37
31

十六进制,前缀0x

>>> 0x1f
31

这在描述二进制标志、代码中的文件权限或颜色的十六进制值时非常有用-例如,请注意不要引号:

>>> 0b10101 # binary flags
21
>>> 0o755 # read, write, execute perms for owner, read & ex for group & others
493
>>> 0xffffff # the color, white, max values for red, green, and blue
16777215

使模糊的Python 2八进制与Python 3兼容

如果在Python 2中看到以0开头的整数,则这是(不推荐使用的)八进制语法。

>>> 037
31

这很糟糕,因为它看起来应该是37。因此在Python 3中,它现在引发了一个SyntaxError:

>>> 037
  File "<stdin>", line 1
    037
      ^
SyntaxError: invalid token

将Python 2八进制转换为同时在2和3中使用0o前缀的八进制:

>>> 0o37
31