如何在不使用try / except的情况下检查字符串是否可以转换为浮点数或整数值?

问题描述

我有第一年编程课的作业,其中一部分是将字符串转换为整数或浮点值。但是,如果字符串不可转换,则应将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标记为正确。但是我的同学代码没有给出负值,而我的则没有。教授说不允许使用try / except。

解决方法

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

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())

现在,您必须自己了解它的作用,因为您可能需要向您的老板解释它

,

一种确定此方法的方法是尝试进行转换以查看是否可以成功完成转换。无法使用异常会使任务难以完成,这令人惊讶,因为它需要在内部使用许多标记变量。就是说,我认为这涵盖了大多数(即使不是全部)可能性。

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

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