关于解析:如何在python中将字符串解析为float或int?

How do I parse a string to a float or int in Python?

在python中,如何将像"545.2222"这样的数字字符串解析为其相应的浮点值545.2222?或者将字符串"31"解析为整数31

我只想知道如何将float str解析为float,以及(分别)int str解析为int

  • 作为一般规则,如果您在Python中有一个对象,并且想要转换为该类型的对象,那么可以在该对象上调用type(my_object)。结果通常可以作为函数调用来进行转换。例如,type(100)生成int,所以可以调用int(my_object)尝试将my_object转换为整数。这并不总是有效的,但在编码时是一个很好的"第一猜测"。


1
2
3
4
5
>>> a ="545.2222"
>>> float(a)
545.22220000000004
>>> int(float(a))
545

  • 只是想知道为什么最后会有"04"?为什么不简单地说"00"?另外,我当前版本的python没有"04"。
  • @Mangatraimodi浮点数在表示小数时天生不完美。有关更多信息,请参阅stackoverflow.com/q/21895756/931277
  • 为什么不简单地用int(a)而用int(float(a))呢?
  • int(a)将给出字符串不是有效整数的错误:ValueError: invalid literal for int() with base 10: '545.222',但支持从float转换为int。
  • 如果你想安全的话,你应该处理ValueError
  • 如果用"2456123456"这样的数字表示怎么办?
  • 为什么我的python 3.7.2repl没有显示这些跟踪错误?
  • @戴维帕克斯,出于某种原因,皮哈姆不喜欢我做int(float(a))的时候。给我一个警告:Expected type Union[str, bytes, SupportsInt], got float instead。为什么会这样?我不知道他们为什么不喜欢它(从我所知道的来看,这个功能完全按预期工作)。
  • @Samcreamer我正在运行Pycharm 2018.3,我对int(float("545.2222"))没有问题。你确定a不是意外的吗?type(a)print(a)进行验证。
  • @davidmarks hey david,a在本例中,实际上是来自表单输入(文本)。所以它会类似于a = request.POST.get('test')。也许这就是原因?我猜,a的类型应该是一个字符串,当我有机会的时候,它会再次检查。谢谢你的调查,不过不用担心,只是好奇而已。


1
2
3
4
5
def num(s):
    try:
        return int(s)
    except ValueError:
        return float(s)

  • 隐式混合浮点/整数可能会导致细微的错误,这是因为使用浮点时可能会丢失精度,或者对于浮点/整数上的/运算符的不同结果。根据上下文,最好返回int或float,而不是两者都返回。
  • @J.F.Sebastian你是完全正确的,但有时你想让输入决定它是哪一个。让输入指定哪一个可以很好地进行duck输入。
  • 您可以嵌套另一个try,以便在不能转换为浮动时抛出异常。
  • s = u'\u0000'失败
  • @好主意!我建议把ValueError扔到对应的except中:p
  • 正是我需要的,谢谢!我需要输入命令类型。


Python method to check if a string is a float:

1
2
3
4
5
6
def is_float(value):
  try:
    float(value)
    return True
  except:
    return False

这个函数的长度和精度可以是:is_convertible_to_float(value)

什么是,也不是Python中的一个浮动

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
val                   is_float(val) Note
--------------------  ----------   --------------------------------
""                    False        Blank string
"127"                 True         Passed string
True                  True         Pure sweet Truth
"True"                False        Vile contemptible lie
False                 True         So false it becomes true
"123.456"             True         Decimal
"      -127   "      True         Spaces trimmed
"\t
12

"
         True         whitespace ignored
"NaN"                 True         Not a number
"NaNanananaBATMAN"    False        I am Batman
"-iNF"                True         Negative infinity
"123.E4"              True         Exponential notation
".1"                  True         mantissa only
"1,234"               False        Commas gtfo
u'\x30'               True         Unicode is fine.
"NULL"                False        Null is not special
0x3fade               True         Hexadecimal
"6e7777777777777"     True         Shrunk to infinity
"1.797693e+308"       True         This is max value
"infinity"            True         Same as inf
"infinityandBEYOND"   False        Extra characters wreck it
"12.34.56"            False        Only one dot allowed
u'四'                 False        Japanese '4' is not a float.
"#56"                 False        Pound sign
"56%"                 False        Percent of what?
"0E0"                 True         Exponential, move dot 0 places
0**0                  True         0___0  Exponentiation
"-5e-5"               True         Raise to a negative number
"+1e1"                True         Plus is OK with exponent
"+1e1^5"              False        Fancy exponent not interpreted
"+1e1.3"              False        No decimals in exponent
"-+1"                 False        Make up your mind
"(1)"                 False        Parenthesis is bad

你知道号码是什么吗?你不太好!不是大惊喜

  • 请考虑将您的函数重命名为convertibleToFloat或类似的名称(至少对我来说,当前的名称似乎很混乱)。
  • 所以真的变成了1,这是我从C++中继承下来的。
  • 好的一个,四也是中文(无关的东西:)
  • 我在2014年发布了这个答案。根据StackOverflow开发人员如何根据微软工具栈更改字符编码方案,中国4UTF-8字形在过去几年中一直在发生变化。当新的转换方案坚持其新的意识形态时,人们很好奇看到它在过去的几年里发生了翻天覆地的变化。但是,任何东方数字的UTF-8字形都不是python float。Bazinga。
  • 怎么会有如此大的例外,如此乐观呢?


This is another method which deserves to be mentioned here,ast.literal&u eval:

This can be used for safely evaluating strings containing Python expressions from untrusted sources without the need to parse the values oneself.

这是一个安全的伊凡

1
2
3
4
5
>>> import ast
>>> ast.literal_eval("545.2222")
545.2222
>>> ast.literal_eval("31")
31

  • 这不是解决问题的好办法。它在python 2中可以很好地工作,但在python 3中会发生以下情况:python >>> import ast >>> ast.literal_eval('1-800-555-1212') -2566 >>> 为了阐明这是一个问题的原因,如果您希望它只保留电话号码,而不假定它们是数学表达式,那么这种方法不适合您。
  • @Royce3是的,这是一个很好的观点,用户应该小心。最初修改行为是为了解决复杂文本解析的一些问题。这可以说是ast.literal_eval中的一个bug,这里已经讨论过了。


1
float(x) if '.' in x else int(x)

  • 吹毛求疵:不适用于极端情况,如浮动("2E-3")。
  • 注意:当处理作为字符串传递的金额时要小心,因为有些国家使用","作为小数点分隔符
  • @埃米尔:我不认为"2E-3"是"极端情况"。这个答案是错误的。
  • @笨蛋不会把钱当作浮点数来操纵。那是自找麻烦。用小数表示钱!(但您对''的评论仍然有效且重要)
  • 不要忘记"not a number"(NaN)和+/-Infinity也是有效的浮点值。因此,float("nan")是一个完全有效的浮点值,上面的答案根本无法捕捉到。
  • 容易被IP地址破坏-192.168.0.1"This is not a good approach. :)"


局部化

你应该考虑在一个号码的字符串代表中,例如float("545,545.2222")的可能性,因为这是一个例外。将弦转换成正确的数字和解释符号。方法转换成一步一步的浮动,直到当地制定了一项有望的公约。

Example 1-United States Number Conventions

在美国和联合王国,可以作为一个分离器使用。In this example with American local,the Comma is handled properly as a separator:

1
2
3
4
5
6
7
8
9
>>> import locale
>>> a = u'545,545.2222'
>>> locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
'en_US.UTF-8'
>>> locale.atof(a)
545545.2222
>>> int(locale.atof(a))
545545
>>>

Example 2-European number conventions

在世界上大多数国家,用以判定一个时期内的马尔卡。In this example with French Local,the Comma is right handled as a decimal mark:

1
2
3
4
5
6
>>> import locale
>>> b = u'545,2222'
>>> locale.setlocale(locale.LC_ALL, 'fr_FR')
'fr_FR'
>>> locale.atof(b)
545.2222

该方法也可用,但论据应该是一个整体。

  • 当您知道是否应该返回float或int时,这似乎是一个理想的解决方案,但是只有传递了int时,如何才能让它返回int?例如,当我实际需要1时,x = '1'; locale.atof(x)返回1.0
  • 用迪诺的方法,我想答案应该是用这样的东西:locale.atof(x) if locale.localeconv().get('decimal_point') in x else locale.atoi(x)
  • 我建议使用上面的Javier方法(在尝试中包装locale.atoi,在例外情况下使用locale.atof,它可能更可读。


用户密码和哈雷是正确的,但如果你知道弦乐是一个整数(例如545),你可以不首先铸造流量。

如果你的弦乐在列表中,你可以使用图表功能。

ZZU1

如果他们都是同一个人,那就好了

  • 用于python 3的list(map(float, x))


如果你不下雨到第三个派对模块,你可以检查一下时尚模块。It provides a function called fast real that does exactly what this question is asking for for and does it faster than a pure-python implementation:

1
2
3
4
5
6
7
8
9
>>> from fastnumbers import fast_real
>>> fast_real("545.2222")
545.2222
>>> type(fast_real("545.2222"))
float
>>> fast_real("31")
31
>>> type(fast_real("31"))
int

这个问题看起来有点老。但让我提出一个功能,Parsestr,它使一些相似的功能,即,返回的积分或浮动,如果一个Given ASCII字符串不能被转换成任何一个它没有触摸。The code of course might be adjusted to do only what you want:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
   >>> import string
   >>> parseStr = lambda x: x.isalpha() and x or x.isdigit() and \
   ...                      int(x) or x.isalnum() and x or \
   ...                      len(set(string.punctuation).intersection(x)) == 1 and \
   ...                      x.count('.') == 1 and float(x) or x
   >>> parseStr('123')
   123
   >>> parseStr('123.3')
   123.3
   >>> parseStr('3HC1')
   '3HC1'
   >>> parseStr('12.e5')
   1200000.0
   >>> parseStr('12$5')
   '12$5'
   >>> parseStr('12.2.2')
   '12.2.2'

  • 1e3是python中的一个数字,但根据代码,它是一个字符串。


In Python, how can I parse a numeric string like"545.2222" to its corresponding float value, 542.2222? Or parse the string"31" to an integer, 31?
I just want to know how to parse a float string to a float, and (separately) an int string to an int.

你要求分开做这些很好。如果你把它们混在一起,以后你可能会遇到麻烦。简单的答案是:

"545.2222"浮动:

1
2
>>> float("545.2222")
545.2222

"31"变为整数:

1
2
>>> int("31")
31

其他转换、与字符串和文字之间的整数:

转换不同的基,您应该提前知道基(默认为10)。注意,您可以为它们加上python对其文本期望的前缀(见下文),或者删除前缀:

1
2
3
4
5
6
7
8
9
10
11
12
>>> 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可以为您推断:

1
2
3
4
5
6
>>> int("0b11111", 0)
31
>>> int('0o37', 0)
31
>>> int('0x1f', 0)
31

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

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

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

二进制,前缀0b

1
2
>>> 0b11111
31

八进制,前缀0o

1
2
>>> 0o37
31

十六进制,前缀0x

1
2
>>> 0x1f
31

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

1
2
3
4
5
6
>>> 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兼容

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

1
2
>>> 037
31

这很糟糕,因为它看起来应该是37。所以在python 3中,它现在提出了一个SyntaxError

1
2
3
4
5
>>> 037
  File"<stdin>", line 1
    037
      ^
SyntaxError: invalid token

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

1
2
>>> 0o37
31

与EDOCX1&1

  • 如果您的字符串恰好是"0"或"0.0",而不是它为其他有效数字提供的int,那么这将为您提供一个float对象。


亚穆尔帕瑟可以帮助你输出你的数据类型。使用yaml.load(),然后你可以使用type(result)测试类型:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
>>> import yaml

>>> a ="545.2222"
>>> result = yaml.load(a)
>>> result
545.22220000000004
>>> type(result)
<type 'float'>

>>> b ="31"
>>> result = yaml.load(b)
>>> result
31
>>> type(result)
<type 'int'>

>>> c ="HI"
>>> result = yaml.load(c)
>>> result
'HI'
>>> type(result)
<type 'str'>

我用这个函数

1
2
3
4
5
6
7
import ast

def parse_str(s):
   try:
      return ast.literal_eval(str(s))
   except:
      return

它将把字符串转换成它的类型

1
2
value = parse_str('1')  # Returns Integer
value = parse_str('1.5')  # Returns Float

1
2
3
4
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

  • 如果你在那里什么都不做,你为什么要在你的except部门增加工资?float()将为您提升。
  • 你是对的,我想我复制并粘贴了一个我提出了一个特殊例外的功能。将编辑。谢谢
  • 这将尝试分析一个字符串,并根据字符串所代表的内容返回intfloat。它可能会增加解析异常或[有一些意外的行为][1]。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def num(s):
"""num(s)
num(3),num(3.7)-->3
num('3')-->3, num('3.7')-->3.7
num('3,700')-->ValueError
num('3a'),num('a3'),-->ValueError
num('3e4') --> 30000.0
"""

try:
    return int(s)
except ValueError:
    try:
        return float(s)
    except ValueError:
        raise ValueError('argument is not a string of number')

你需要先到帐户开着,这样就行了。

I.E.INT(5.1)=>5Int(5.6)=>5-wrong,should be 6 so we do int(5.6+0.5)=>6

1
2
3
4
5
def convert(n):
    try:
        return int(n)
    except ValueError:
        return float(n + 0.5)

  • 好点。但这会导致通货膨胀,所以python 3和其他现代语言使用银行家的四舍五入。
  • 这个答案是错误的(正如最初写的那样)。它混淆了intfloat两种情况。当n是一个字符串时,它将给出一个例外,正如op所希望的那样。也许你的意思是:当需要一个int结果时,round应该在转换为float之后完成。如果函数总是返回一个int,那么不需要except部分——整个函数体可以是int(round(float(input)))。如果函数可能返回一个int,否则返回一个float,那么javier的原始解决方案是正确的!


我很惊讶没有人提到regex,因为有时字符串必须在转换为数字之前准备好并规范化。

1
2
3
4
5
6
7
8
9
10
import re
def parseNumber(value, as_int=False):
    try:
        number = float(re.sub('[^.\-\d]', '', value))
        if as_int:
            return int(number + 0.5)
        else:
            return number
    except ValueError:
        return float('nan')  # or None if you wish

用途:

1
2
3
4
5
6
7
8
9
parseNumber('13,345')
> 13345.0

parseNumber('- 123 000')
> -123000.0

parseNumber('99999
'
)
> 99999.0

顺便说一下,要验证一下你有一个数字:

1
2
3
4
import numbers
def is_number(value):
    return isinstance(value, numbers.Number)
    # will work with int, float, long, Decimal

Python在一行程序中具有很强的解析灵活性。

1
2
3
str ="545.2222"
print ("int:", + int(float(a)))
print ("float:", +(float(a)))

要在python中进行类型转换,请使用类型的构造函数函数,将字符串(或您尝试转换的任何值)作为参数传递。

例如:

1
2
>>>float("23.333")
   23.333

在幕后,python调用对象__float__方法,该方法将返回参数的浮点表示。这特别强大,因为您可以使用__float__方法定义自己的类型(使用类),以便使用float(myObject)将其强制转换为float。


这是正确的版本https://stackoverflow.com/a/33017514/5973334

这将尝试分析一个字符串,并根据该字符串所代表的内容返回intfloat。它可能会增加解析异常或有一些意外的行为。

1
2
3
4
5
  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

您可以使用str()将任何变量转换为字符串,int()将字符串整数转换为整数,float()将字符串浮点数转换为浮点值。

1
2
str_to_float = float("545.2222")
str_to_int = int("31")

用途:

1
2
3
4
5
6
7
8
9
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()

这是我能想到的最Python的方法。


如果知道str,它可以是int或float:

1
return int(s) if s.isdigit() else float(s)

  • 如果字符串不是数字,那么float也不会工作。
  • @vignesht.v.-如果字符串是'545.2222',那么'545.2222'.isdigit()返回false,所以函数返回545.2222;否则,如果字符串是'31',那么'31'.isdigit()返回true,函数返回31


用途:

1
2
3
4
5
6
7
8
9
10
11
>>> str_float ="545.2222"
>>> float(str_float)
545.2222
>>> type(_) # Check its type
<type 'float'>

>>> str_int ="31"
>>> int(str_int)
31
>>> type(_) # Check its type
<type 'int'>


这是对你问题的另一种解释(Hint:这是模糊的)。你可能在找像这样的东西

1
2
def parseIntOrFloat( aString ):
    return eval( aString )

它就像这样工作

1
2
3
4
>>> parseIntOrFloat("545.2222")
545.22220000000004
>>> parseIntOrFloat("545")
545

理论上,注射脆弱性。弦乐可以以"import os; os.abort()"为例。没有任何背景,弦乐从哪里来,但可能性是理论上的模型。既然这个问题很模糊,那么,如果这种脆弱性实际存在或不存在,这一点就不清楚。

  • 即使他的输入是100%安全的,eval()的速度也比try: int(s) except: float(s)慢3倍多。
  • 嗯,eval是个坏习惯(你必须知道,因为你有310K的声誉)