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



我为第一年的编程类分配了一项任务,其中一部分是将字符串转换为整数或浮点值。但是,如果字符串不可转换,则应将值None传递给变量。我的教授指出,无论出于何种原因,我们都不允许使用try/,我唯一能想到的方法是使用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

使用这个,教授使用的自动标记器将其标记为正确,同时也标记我的尝试/除外正确。但我的同学代码没有给出负值,我的代码也没有。教授说不允许尝试。

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

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

最新更新