What is the best possible way to check if a string can be represented as a number in Python?
The function I currently have right now is:
def is_numb
I needed to determine if a string cast into basic types (float,int,str,bool). After not finding anything on the internet I created this:
def str_to_type (s):
""" Get possible cast type for a string
Parameters
----------
s : string
Returns
-------
float,int,str,bool : type
Depending on what it can be cast to
"""
try:
f = float(s)
if "." not in s:
return int
return float
except ValueError:
value = s.upper()
if value == "TRUE" or value == "FALSE":
return bool
return type(s)
Example
str_to_type("true") # bool
str_to_type("6.0") # float
str_to_type("6") # int
str_to_type("6abc") # str
str_to_type(u"6abc") # unicode
You can capture the type and use it
s = "6.0"
type_ = str_to_type(s) # float
f = type_(s)