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
.
This is another method which deserves to be mentioned here, ast.literal_eval:
That is, a safe 'eval'
The question seems a little bit old. But let me suggest a function, parseStr, which makes something similar, that is, returns integer or float and if a given ASCII string cannot be converted to none of them it returns it untouched. The code of course might be adjusted to do only what you want:
Here's another interpretation of your question (hint: it's vague). It's possible you're looking for something like this:
It works like this...
Theoretically, there's an injection vulnerability. The string could, for example be
"import os; os.abort()"
. Without any background on where the string comes from, however, the possibility is theoretical speculation. Since the question is vague, it's not at all clear if this vulnerability actually exists or not.Python method to check if a string is a float:
A 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:
You think you know what numbers are? You are not so good as you think! Not big surprise.
I use this function for that
It will convert the string to its type