Testing if Python string variable holds number (int,float) or non-numeric str?

前端 未结 6 867
情书的邮戳
情书的邮戳 2020-12-19 11:23

If a Python string variable has had either an integer, floating point number or a non-numeric string placed in it, is there a way to easily test the \"type\" of that value?<

相关标签:
6条回答
  • 2020-12-19 11:31

    Here is a short hand to do it without ast import

        try:
            if len(str(int(decdata))) == len(decdata): return 'int'
        except Exception:
            return 'not int'
    

    Of course 's' is the string you want to evaluate

    0 讨论(0)
  • 2020-12-19 11:35

    I'd do it like this:

    def typeofvalue(text):
        try:
            int(text)
            return int
        except ValueError:
            pass
    
        try:
            float(text)
            return float
        except ValueError:
            pass
    
        return str
    
    0 讨论(0)
  • 2020-12-19 11:40

    You can check if a variable is numeric using the built-in isinstance() function:

    isinstance(x, (int, long, float, complex))
    

    This also applies to string and unicode literal types:

    isinstance(x, (str, unicode))
    

    For example:

    def checker(x):
        if isinstance(x, (int, long, float, complex)):
            print "numeric"
        elif isinstance(x, (str, unicode)):
            print "string"
    

    >>> x = "145"
    >>> checker(x)
    string
    >>> x = 145
    >>> checker(x)
    numeric
    
    0 讨论(0)
  • I'd use a regular expression

    def instring (a):
    
      if re.match ('\d+', a):
        return int(a)
      elsif re.match ('\d+\.\d+', a):
        return float(a)
      else:
        return str(a)
    
    0 讨论(0)
  • 2020-12-19 11:42

    use .isdigit():

    In [14]: a = '145'
    
    In [15]: b = 'foo'
    
    In [16]: a.isdigit()
    Out[16]: True
    
    In [17]: b.isdigit()
    Out[17]: False
    
    In [18]: 
    
    0 讨论(0)
  • 2020-12-19 11:51
    import ast
    def type_of_value(var):
        try:
           return type(ast.literal_eval(var))
        except Exception:
           return str
    

    Or, if you only want to check for int, change the third line to block inside try with:

    int(var)
    return int
    
    0 讨论(0)
提交回复
热议问题