def check_float(s:str): if s.count('.')==1: a = s.split('.')[0] b = s.split('.')[1] if a.isdigit() and b.isdigit(): print('%s 为正整数'%(s)) return s else: if a.startswith('-') and a.count('-') == 1: print('%s 为负整数'%(s)) return s else: print('非小数') check_float('1.5') #正小数 1.5 #1、小数点个数必须为1-->'1.5'.count('.')==1 #2、小数点左右与两边都是整数-->'1.5'.split('.').isdigit() #负小数 -1.5 #1、小数点个数必须为1-->'1.5'.count('.')==1 #2、小数点左右与两边都是整数-->'1.5'.split('.').isdigit() #3、符号开头,并且只有一个负号-->'1.5'.startwith() def check_float(s): ''' 这个函数的作用就是判断传入的字符串是否是合法的小数 :param s: 传入一个字符串 :return: True/False ''' s = str(s) if s.count('.') == 1: s_split = s.split('.') #1.5 [1,5] left,right = s_split #等价于left=s_splilt[0] right = s_split[1] if left.isdigit() and right.isdigit(): return True elif left.startswith('-') and left[1:].isdigit() and right.isdigit(): return True return False #假如传一个整数,例如4,直接走到该处 print(check_float(1.3)) print(check_float(-1.3)) print(check_float('1.3')) print(check_float('-1.3')) print(check_float('--1.2')) print(check_float('2.3w3')) print(check_float('22s.4'))
python3学习(八)--小数校验
猜你喜欢
转载自www.cnblogs.com/xm-sunnylin/p/9641797.html
今日推荐
周排行