'How do I check if a string is a float number or an integer number?
"1.0".isnumeric() -> False
I need to know if that string is actually a float number or an integer number because there although the string is in fact a float number the .isnumeric() returns False
Solution 1:[1]
What you can do is convert the string into its actual datatype using ast.literal_eval method and then use the isinstance method to check if it is a float number or not.
>>> import ast
>>> string = '1.0'
>>>
>>> num = ast.literal_eval(string)
>>> num
1.0
>>> isinstance(num,float)
True
>>>
Same way you can check if it is an integer. Hope this answers your question.
Solution 2:[2]
Try this function:
def is_numeric(some_string):
try:
float(some_string)
return True
except ValueError:
return False
if __name__ == "__main__":
print(is_numeric("123"))
print(is_numeric("1.0"))
print(is_numeric("1.0asd"))
Output:
True
True
False
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | tall-e.stark |
| Solution 2 | Savostyanov Konstantin |
