【问题标题】:How do I check if a string can be converted to a float or integer value without using try/except?如何在不使用 try/except 的情况下检查字符串是否可以转换为浮点或整数值?
【发布时间】:2021-02-11 07:46:39
【问题描述】:

我在第一年的编程课上有一个作业,其中一个部分是将字符串转换为整数或浮点值。但是,如果字符串不可转换,则应将值 None 传递给变量。我的教授表示,无论出于何种原因,我们都不允许使用 try/except,我能想到的唯一方法是使用 isdigit() 方法,但是,这不适用于所需的负值,因为值是用于测量温度。

temp = input('What is the temperature value? Enter a numeric value: ')

try: 
   temp = float(input('What is the temperature value? Enter a numeric value: '))
except ValueError:
   temp = None

这是我能想到的唯一方法,但是,我班的另一个学生在我们应该定义的先前函数之一中使用 is digit() 做到了

def convert_to_kelvin(temperature, units):
    unit = units.lower()
    if type(temperature) != float and type(temperature) != int and temperature.isdigit() == False:
   return None

使用它,教授使用的自动评分器将其标记为正确,它也将我的尝试/除外标记为正确。但是我的同学代码没有给出负值,而我的没有。教授说 try/except 是不允许的。

【问题讨论】:

  • 去掉负号,处理,再把负号加回去?所以如果s的第一个字符是'-',就做isdigit(s[1:]),如果不是,就用isdigit(s)——这符合你的要求吗?
  • 对不起,我对编程很陌生。如何删除负号并将其添加回来?
  • 您的代码是否需要与int()float() 完全一样?

标签: python floating-point integer try-except


【解决方案1】:

所以这是我的尝试,我不知道它是否真的适用于所有情况,但就我测试而言:

allowed_chars = '1234567890.-'

temp = input('Input temp: ')

def check():
    not_int = False
    for chars in temp:
        if chars not in allowed_chars or temp[-1] == '.' or temp[-1] == '-':
            not_int = True
        else:
            not_int = False
    return temp if not not_int else None

print(check())

现在你必须自己理解它的作用,因为你可能需要向你的教授解释它

【讨论】:

  • 对不起,-1 索引对温度意味着什么?
  • @AmmarAhmed 这是最后一个值,如果有人输入123.,那么它既不是整数也不是浮点数
【解决方案2】:

确定这一点的一种方法是尝试进行转换以查看是否可以成功完成。无法使用异常使任务难以正确完成,因为它需要在内部使用大量标志变量。话虽如此,我认为这里的内容涵盖了大部分(如果不是全部)可能性。

这是这种方法的一个弱点,因为存在大量无效的可能输入,而有效输入的数量相对较少。

from string import digits  # '0123456789'


def parse_numeric(string):
    """ Parse a string into an integer or float if possible and return it,
        otherwise return None.
    """
    if not string:  # Empty string?
        return None
    decimal_point = None
    neg = False
    if string.startswith('-'): # minus sign?
        string = string[1:]  # Remove it.
        neg = True

    res = 0
    for ch in string:
        if ch == '.':  # Decimal point?
            if decimal_point is not None:
                return None  # Invalid, one already seen.
            else:
                decimal_point = 0  # Initialize.
                continue

        if ch not in digits:
            return None  # Invalid.
        if decimal_point is not None:
            decimal_point += 1
        res = res*10 + ord(ch) - ord('0')

    if decimal_point is not None:
        res = res / 10**decimal_point
    return res if not neg else -res


if __name__ == '__main__':

    testcases = ('1', '12', '123', '123.', '123.4', '123.45',
                 '-1', '-12', '-123', '-123.', '-123.4', '-123.45',
                 '1-', '-1-2', '123-4.5', 'foobar', '-woot')

    for temp in testcases:
        print(f'input: {temp!r:>10}, result: {parse_numeric(temp)}')

输出:

input:        '1', result: 1
input:       '12', result: 12
input:      '123', result: 123
input:     '123.', result: 123.0
input:    '123.4', result: 123.4
input:   '123.45', result: 123.45
input:       '-1', result: -1
input:      '-12', result: -12
input:     '-123', result: -123
input:    '-123.', result: -123.0
input:   '-123.4', result: -123.4
input:  '-123.45', result: -123.45
input:       '1-', result: None
input:     '-1-2', result: None
input:  '123-4.5', result: None
input:   'foobar', result: None
input:    '-woot', result: None

【讨论】:

  • Matiiss:这不是回答你的问题吗?
猜你喜欢
  • 2010-12-28
  • 1970-01-01
  • 2010-10-18
  • 2015-01-01
  • 1970-01-01
  • 2016-10-07
  • 1970-01-01
  • 1970-01-01
  • 2017-03-01
相关资源
最近更新 更多