How to resolve a string to float or int?

Posted by schme16 on Sat, 07 Dec 2019 16:18:28 +0100

In Python, how to parse the number string of "545.2222" class into its corresponding floating-point value 545.2222? Or parse the string "31" to the integer 31?

I just want to know how to parse float of float str and (respectively) an int str to int.

#1 building

YAML A parser can help you determine what data type a string is. Use yaml.load() and then use type(result) to test the type:

>>> 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'>

#2 building

Localization and commas

You should consider the possibility of commas in the string representation of numbers, such as when an exception is thrown for float ("545545.2222"). Instead, use the locale method to convert the string to a number and interpret the comma correctly. Once the locale is set up for the desired number convention, the locale.atof method converts one step into a floating-point number.

Example 1 - US digital conventions

In the United States and the United Kingdom, commas can be used as thousands separators. In this example with the U.S. locale, the comma is treated correctly as a separator:

>>> 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 digital Convention

in the world Most countries , comma for decimal point instead of period. In this example using the French locale, commas are properly treated as decimal points:

>>> import locale
>>> b = u'545,2222'
>>> locale.setlocale(locale.LC_ALL, 'fr_FR')
'fr_FR'
>>> locale.atof(b)
545.2222

You can also use the method locale.atoi, but the argument should be an integer.

#3 building

Python method to check if the string is a floating-point number:

def is_float(value):
  try:
    float(value)
    return True
  except:
    return False

The longer, more accurate name for this function might be: is ﹐ convertible ﹐ to ﹐ float (value)

What is? Python medium Instead of floating-point numbers, you might be surprised:

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\n12\r\n"          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'Four'                 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

What number do you think you know? You are not as good as you think! Not surprisingly.

Don't use this code on life critical software!

In this way, we can catch a wide range of exceptions. Killing canaries and devouring exceptions will have a very small chance, that is, the valid float string will return false. The float(...) line of code can fail for thousands of reasons unrelated to the content of the string. But if you're writing critical software in a duck archetypal language like Python, you're going to have a bigger problem.

#4 building

If you don't like third-party modules, you can check them out fastnumbers Modular. It provides a fast_real This function can fully meet the requirements of this problem, and is faster than the pure Python implementation:

>>> 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

#5 building

In Python, how to parse a numeric string such as "545.2222" into its corresponding floating-point value 542.2222? Or parse the string "31" to the integer 31? I just want to know how to parse the float string into float and the int string into int respectively.

You'd better do these alone. If you want to mix them, you may encounter problems later. The simple answer is:

"545.2222" float:

>>> float("545.2222")
545.2222

"31" is an integer:

>>> int("31")
31

Other conversion between string and text, integer conversion:

For transformations from various datums, you should know the datums in advance (the default is 10). Note that you can add the literal amount Python expects (see below) or remove the prefix:

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

If you don't know the cardinality in advance, but you know they will have the correct prefix, Python can infer for you if you use 0 as the cardinality:

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

Non decimal (i.e. integer) text for other Radix

However, if your motivation is to have your code clearly represent hard coded specific values, you may not need to convert the cardinality - you can let Python do it for you automatically using the correct syntax.

You can use the apropos prefix to automatically convert to a Of Integer. These work for Python 2 and 3:

Binary, prefix 0b

>>> 0b11111
31

Octal, prefix 0o

>>> 0o37
31

Hex, prefix 0x

>>> 0x1f
31

This is useful when describing binary flags, file permissions in code, or hexadecimal values for colors - for example, be careful not to use quotation marks:

>>> 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

Make ambiguous Python 2 octal compatible with Python 3

If you see an integer starting with 0 in Python 2, this (not recommended) octal syntax.

>>> 037
31

This is bad because it looks like the value should be 37. So in Python 3, it now raises a SyntaxError:

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

Use the 0o prefix to convert Python 2 octal to octal that can be used in both 2 and 3:

>>> 0o37
31

Topics: Python