Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing if Python string variable holds number (int,float) or non-numeric str?

Tags:

python

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'>
like image 580
PolyGeo Avatar asked Oct 07 '11 03:10

PolyGeo


People also ask

How do I check if a string contains a non numeric character in Python?

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 .

How do you check if a string is an integer or int?

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.

How do you check if a string contains numbers in Python?

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.


1 Answers

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
like image 61
JBernardo Avatar answered Sep 22 '22 04:09

JBernardo