【问题标题】:How to check if string is (int or float) in Python 2.7如何在 Python 2.7 中检查字符串是否为(int 或 float)
【发布时间】:2016-03-29 07:01:21
【问题描述】:

我知道之前有人问过并回答过类似的问题:How do I check if a string is a number (float) in Python?

但是,它没有提供我正在寻找的答案。我想要做的是:

def main():
    print "enter a number"
    choice = raw_input("> ")
    # At this point, I want to evaluate whether choice is a number.
    # I don't care if it's an int or float, I will accept either.

    # If it's a number (int or float), print "You have entered a number."
    # Else, print "That's not a number."
main()

大多数问题的答案都建议使用 try..except,但这仅允许我专门评估 int 或 floats,即

def is_number(s):
    try:
        float(choice)
        return True
    except ValueError:
        return False

如果我使用此代码,int 值将在异常中结束。

我见过的其他方法包括 str.isdigit。但是,这对于 int 返回 True,对于 float 则返回 false。

【问题讨论】:

  • float('123') 返回123.0 并且不给你ValueError。所以你的功能工作正常。
  • “如果我使用此代码,int 值将出现在异常中” - 不。请在询问之前实际尝试这些事情。
  • 感谢各位的澄清。在问这个之前我确实尝试过这种方法,但我无法让它发挥作用。一定是在某个地方犯了错误。无论哪种方式,它现在就像你们提到的那样工作。谢谢!!
  • 这能回答你的问题吗:Checking whether a variable is an integer or notThomas

标签: python string floating-point int


【解决方案1】:

在您的情况下,只需检查输入是否可以在 try/except 块中转换为浮点数就足够了。对于任何可以转换为整数的字符串,转换都将成功。

【讨论】:

    【解决方案2】:

    您使用的函数应该成功地将字符串形式的 int 和 float 值转换为 float。出于某种原因,您特别想查找天气是 int 还是 float,请考虑此更改。

    def is_int_or_float(s):
        ''' return 1 for int, 2 for float, -1 for not a number'''
        try:
            float(s)
    
            return 1 if s.count('.')==0 else 2
        except ValueError:
            return -1
    print is_int_or_float('12')
    print is_int_or_float('12.3')
    print is_int_or_float('ads')
    

    这是结果

    python test.py
    1
    2
    -1
    

    【讨论】:

      【解决方案3】:

      你可以自己写函数,

      def is_int_or_float(a):
          if type(a) is int or type(a) is float:
              return True
          else:
             return False
      

      您可以编写更紧凑的程序。之间请自己做。

      谢谢!

      【讨论】:

        【解决方案4】:

        您可以使用isstance() 方法和literal_eval

        例子

        from ast import literal_eval
        
           isinstance(literal_eval('3'),int)
        

        返回

        True
        

        或者你可以使用json。

        import json
        
        isinstance(json.loads('3'),int)
        

        返回

        True
        

        【讨论】:

          【解决方案5】:

          我知道这是旧的,但我做了一个简单的检查:

              var = 3
          
              try: #if it can be converted to a float, it's true
                  float(var) 
              except: # it it can't be converted to a float, it's false
                  do stuff with the var 
          

          【讨论】:

            猜你喜欢
            • 2016-08-05
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-04-30
            • 2011-02-20
            • 2016-06-27
            • 2013-03-04
            • 1970-01-01
            相关资源
            最近更新 更多