如何在Python中检查字符串是否表示数值?
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
上述方法可行,但似乎很笨拙。
如果您正在测试的内容来自用户输入,那么即使它表示int或float,它仍然是一个字符串。请参阅如何将输入读取为数字?用于转换输入,并询问用户输入,直到他们给出有效响应以确保输入在继续之前表示int或float(或其他要求)。
用户助手功能:
def if_ok(fn, string):
try:
return fn(string)
except Exception as e:
return None
然后
if_ok(int, my_str) or if_ok(float, my_str) or if_ok(complex, my_str)
is_number = lambda s: any([if_ok(fn, s) for fn in (int, float, complex)])
您可以使用Unicode字符串,它们有一种方法可以满足您的需要:
>>> s = u"345"
>>> s.isnumeric()
True
Or:
>>> s = "345"
>>> u = unicode(s)
>>> u.isnumeric()
True
http://www.tutorialspoint.com/python/string_isnumeric.htm
http://docs.python.org/2/howto/unicode.html
用户助手功能:
def if_ok(fn, string):
try:
return fn(string)
except Exception as e:
return None
然后
if_ok(int, my_str) or if_ok(float, my_str) or if_ok(complex, my_str)
is_number = lambda s: any([if_ok(fn, s) for fn in (int, float, complex)])
对于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