If a Python string variable has had either an integer, floating point number or a non-numeric string placed in it, is there a way to easily test the "type" of that value?
The code below is real (and correct of course):
>>> strVar = "145"
>>> print type(strVar)
<type 'str'>
>>>
but is there a Python function or other method that will enable me to return 'int' from interrogating strVar set as above
Perhaps something like the nonsense code and results below ...
>>> print typeofvalue(strVar)
<type 'int'>
or more nonsense:
>>> print type(unquote(strVar))
<type 'int'>
The isnumeric() method returns True if all the characters are numeric (0-9), otherwise False. Exponents, like ² and ¾ are also considered to be numeric values. "-1" and "1.5" are NOT considered numeric values, because all the characters in the string must be numeric, and the - and the .
We can use the isdigit() function to check if the string is an integer or not in Python. The isdigit() method returns True if all characters in a string are digits. Otherwise, it returns False.
To check if a string contains a number in Python:Use the str. isdigit() method to check if each char is a digit. Pass the result to the any() function. The any function will return True if the string contains a number.
import ast
def type_of_value(var):
try:
return type(ast.literal_eval(var))
except Exception:
return str
Or, if you only want to check for int, change the third line to block inside try
with:
int(var)
return int
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With