How can I check if a string represents an int, without using try/except?

前端 未结 19 2126
悲哀的现实
悲哀的现实 2020-11-22 00:36

Is there any way to tell whether a string represents an integer (e.g., \'3\', \'-17\' but not \'3.14\' or \'asf

19条回答
  •  野的像风
    2020-11-22 01:04

    def is_int_or_float(x):
        try:    
            if int(float(x)):
                if float(x).is_integer():  return 'int'
                else:                      return 'float'
        except ValueError:  return False
    
    
    for  i  in ['*', '-1', '01', '1.23', '+0011.002', ]:
        print(i, is_int_or_float(i))
    
    # * False
    # -1 int
    # 01 int
    # 1.23 float
    # +0011.002 float
    

提交回复
热议问题