
- #Python convert string to int different base how to
- #Python convert string to int different base software
It's good that you ask to do these separately.
#Python convert string to int different base how to
I just want to know how to parse a float string to a float, and (separately) an int string to an int. 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? The method locale.atoi is also available, but the argument should be an integer. In this example with French locale, the comma is correctly handled as a decimal mark: > import locale In the majority of countries of the world, commas are used for decimal marks instead of periods. In this example with American locale, the comma is handled properly as a separator: > import locale In the United States and the UK, commas can be used as a thousands separator. The locale.atof method converts to a float in one step once the locale has been set for the desired number convention.Įxample 1 - United States number conventions Instead, use methods in locale to convert the strings to numbers and interpret commas correctly. You should consider the possibility of commas in the string representation of a number, for cases like float("545,545.2222") which throws an exception.
#Python convert string to int different base software
But if you're writing life-critical software in a duck-typing prototype language like Python, then you've got much larger problems. The float(.) line of code can failed for any of a thousand reasons that have nothing to do with the contents of the string. Don't use this code on life-critical software!Ĭatching broad exceptions this way, killing canaries and gobbling the exception creates a tiny chance that a valid float as string will return false. You think you know what numbers are? You are not so good as you think! Not big surprise. "+1e1^5" False Fancy exponent not interpreted "0E0" True Exponential, move dot 0 places "infinityandBEYOND" False Extra characters wreck it "12 34" False Spaces not allowed on interior One confounding difference is that any number of interior underscores are now allowed: (float("1_3.4") = float(13.4)) is True val is_float(val) Note Check it that Python3 has different behavior for what strings are convertable to float. The below unit tests were done using python2. Python2 method to check if a string is a float: def is_float(value):įor the Python3 version of is_float see: Checking if a string can be converted to float in PythonĪ longer and more accurate name for this function could be: is_convertible_to_float(value) What is, and is not a float in Python may surprise you:
