如何在Python中检查字符串是否表示数值?
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
上述方法可行,但似乎很笨拙。
如果您正在测试的内容来自用户输入,那么即使它表示int或float,它仍然是一个字符串。请参阅如何将输入读取为数字?用于转换输入,并询问用户输入,直到他们给出有效响应以确保输入在继续之前表示int或float(或其他要求)。
我需要确定字符串是否转换为基本类型(float、int、str、bool)。在互联网上找不到任何东西后,我创建了这个:
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)
实例
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
您可以捕获类型并使用它
s = "6.0"
type_ = str_to_type(s) # float
f = type_(s)