【问题标题】:Given a string, how do I check if it is a float?给定一个字符串,我如何检查它是否是一个浮点数?
【发布时间】:2019-08-17 15:02:27
【问题描述】:

我必须使用python读取一个文件,这个文件包含字符、数字和其他东西的组合。

从文件中读取一行后,如何检查该行是整数还是浮点数? (我必须知道这条信息,这条线是整数和浮点数)

我试过.isdigit().isdecimal().isnumeric()这些字符串方法,似乎这些方法只在字符串中只有所有十进制数字时才返回True

有什么方法可以帮助我完成这项任务吗?

P.S.:不能使用try 或任何exception 方法。

============== 我的文件内容 =================

0
[Begin Description]
xxx
[End Description]
1.1
[Begin Description]
....

我想知道我正在阅读的当前行是整数 0 还是浮点数 1.1。这就是我的问题。

【问题讨论】:

  • 为什么你不能使用try/except
  • 这实际上是一个家庭作业问题,但我认为这对所有新手来说都是一般性的,所以我在这个大趋势下发布。真的很抱歉。
  • 在可能出现异常时使用try/except 是不好的做法。这使它成为一项相当糟糕的家庭作业。
  • 另外,请显示您的代码和错误消息,以便我们有机会了解发生了什么。
  • 很抱歉,我知道这是行业标准,但真的不能从这个作业中使用它。

标签: python string


【解决方案1】:

希望对你有帮助

import re
s = "1236.0"
r = re.compile(r'[1-9]')
r2 = re.compile(r'(\.)')
if re.search(r,s) and re.search(r2,s):
    print("Float")
if re.search(r,s) and not re.search(r2,s):
    print("Integer")

【讨论】:

    【解决方案2】:

    你应该使用 try 和 except:

    但如果您不想使用它并需要不同的方式,请使用 regex

    if re.match(r"[-+]?\d+(\.0*)?$", s):
       print("match")
    

    【讨论】:

      【解决方案3】:

      对于文件中的每一行,您可以使用正则表达式检查它是浮点数、整数还是普通字符串

      import re
      
      float_match = re.compile("^[-+]?[0-9]*[.][0-9]+$")
      int_match = re.compile("^[-+]?[0-9]+$")
      
      lines = ["\t23\n", "24.5", "-23", "0.23", "-23.56", ".89", "-122", "-abc.cb"]
      
      for line in lines:
          line = line.strip()
      
          if int_match.match(line):
              print("int")
          elif float_match.match(line):
              print("float")
          else:
              print("str")
      
      
      

      结果:

      int
      浮动
      整数
      浮动
      浮动
      浮动
      整数
      字符串

      它是如何工作的: int_match = re.compile("^[-+]?[0-9]+$")

      ^:字符串开头
      [-+]?:可选+或-
      [0-9]+:一个或多个数字
      $:字符串结尾

      float_match = re.compile("^[-+]?[0-9]*[.][0-9]+$")

      ^[-+]?:以 + 或 - 开头,可选。
      [0-9]*:任意位数或无。
      [.]:点
      [0-9]+:一位或多位数字
      $:end

      【讨论】:

        【解决方案4】:

        这比re

        虽然这不是类型检查,但是当您读取字符串 0 或 1.1 时,您可以像

        line='1.1'
        if '.' in line:
            print("float")
        else:
            print("int")
        

        【讨论】:

          【解决方案5】:

          试试这个:

          import re
          line1 = '0'
          line2 = 'description one'
          line3 = '1.1'
          line4 = 'begin description'
          lines = [line1, line2, line3, line4] # with readlines() you can get it directly
          for i in lines:
             if re.findall("[+-]?\d+", i) and not re.findall("[+-]?\d+\.\d+", i):
               print('int found')
             elif re.findall("[+-]?\d+\.\d+", i):
               print('float found')
             else:
               print('no numeric found')
          

          输出

          int found
          no numeric found
          float found
          no numeric found
          

          【讨论】:

            【解决方案6】:

            您可以使用 .split() 将其拆分为单词并使用字符串方法。

            示例代码(请注意,如果您在浮点数而不是点中使用 split 方法参数,则应将其更改为逗号):

            def float_checker(strinput):
                digit_res = None
                for part in strinput.split('.'):
                    digit_res = True if part.isnumeric() else False
                if digit_res:
                    return True
                return False
            
            if __name__ == '__main__':
                while True:
                    print(float_checker(input('Input for float check (Stop with CTRL+C): ')))
            

            【讨论】:

              猜你喜欢
              • 2012-07-21
              • 1970-01-01
              • 2010-10-13
              • 2022-03-31
              • 1970-01-01
              • 2017-12-16
              • 2012-09-10
              相关资源
              最近更新 更多