如何在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)
对于int,请使用以下命令:
>>> "1221323".isdigit()
True
但对于float,我们需要一些技巧;-)。每个浮点数都有一个点。。。
>>> "12.34".isdigit()
False
>>> "12.34".replace('.','',1).isdigit()
True
>>> "12.3.4".replace('.','',1).isdigit()
False
对于负数,只需添加lstrip():
>>> '-12'.lstrip('-')
'12'
现在我们有了一个通用的方法:
>>> '-12.34'.lstrip('-').replace('.','',1).isdigit()
True
>>> '.-234'.lstrip('-').replace('.','',1).isdigit()
False
在浮点数的最常见情况下,我们希望处理整数和小数。让我们以字符串“1.1”为例。
我会尝试以下方法之一:
1.>isnumeric()
word = "1.1"
"".join(word.split(".")).isnumeric()
>>> True
2.>isdigit()
word = "1.1"
"".join(word.split(".")).isdigit()
>>> True
3.>isdecimal()
word = "1.1"
"".join(word.split(".")).isdecimal()
>>> True
速度:
► 所有上述方法具有相似的速度。
%timeit "".join(word.split(".")).isnumeric()
>>> 257 ns ± 12 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
%timeit "".join(word.split(".")).isdigit()
>>> 252 ns ± 11 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
%timeit "".join(word.split(".")).isdecimal()
>>> 244 ns ± 7.17 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)