记录工作中的需求,用Python实现对整数、小数、百分数的判断
def is_number(s):
if s.count(".") == 1 and s[-1] != "%": # 小数的判断
if s[0] == "-":
s = s[1:]
if s[0] == ".":
return False
s = s.replace(".", "")
for i in s:
if i not in "0123456789":
return False
else: # 这个else与for对应的
return True
elif s.count(".") == 0 and s[-1] != "%": # 整数的判断
if s[0] == "-":
s = s[1:]
for i in s:
if i not in "0123456789":
return False
else:
return True
elif s[-1] == "%": # 百分数判断
return True
else:
return False
print(is_number("1334345345"))
print(is_number("1.12344565"))
print(is_number("-14344343"))
print(is_number("-1.123456"))
print(is_number("10%"))
print(is_number("nihao"))
print(is_number("你好"))
输出结果:
True
True
True
True
True
False
False