知识点:字符串
问题描述:
请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100",“5e2”,"-123",“3.1416"和”-1E-16"都表示数值。 但是"12e",“1a3.14”,“1.2.3”,"±5"和"12e+4.3"都不是。
详解:
# -*- coding:utf-8 -*-
class Solution:
# s字符串
def isNumeric(self, s):
# write code here
if s[0]=="+" or s[0]=="-":
if s[1]!="+" and s[1]!="-":
try:
if float(s[1:]):
return True
except:
return False
else:
return False
else:
try:
if float(s):
return True
except:
return False
知识点:
float() 函数用于将整数和字符串转换成浮点数。
class float([x])
- x – 整数或字符串
- 返回浮点数。
实例:
>>>float(1)
1.0
>>> float(112)
112.0
>>> float(-123.6)
-123.6
>>> float('123') # 字符串
123.0