缺少值的元组

2024-05-23 15:08:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我在python中有一个函数可以对字符串进行错误检查。如果函数发现错误,它将返回一个元组,其中包含错误代码和该错误的标识符。在程序的后面,我有一个处理错误的函数。它接受元组为两个变量。在

errCode, i = check_string(s,pathType)

check_string是生成元组的函数。我想让它做的是,如果没有错误,只返回0。当返回0时,上面的代码似乎失败了,因为变量i没有任何内容

有没有一个简单的方法可以让它工作,或者我只需要让程序返回一个0和0的元组,如果没有发现错误?在


Tags: 方法函数字符串代码程序内容stringcheck
3条回答

我会用例外制度。在

class StringError(Exception):
    NO_E = 0
    HAS_Z = 1

def string_checker(string):
    if 'e' not in string:
        raise StringError('e not found in string', StringError.NO_E)
    if 'z' in string:
        raise StringError('z not allowed in string', StringError.HAS_Z)
    return string.upper()

s = 'testing'
try:
    ret = string_checker(s)
    print 'String was okay:', ret
except StringError as e:
    print 'String not okay with an error code of', e.args[1]

可以使用“无”作为错误值

def check_string(s,pathType):
    # No error
    return (None, i)

为什么不在尝试检索值之前简单地检查元组的长度?在

err_tup = check_String(s, pathType)
if len(err_tup) == 2:
    errCode, i = err_tup
else: # assuming it can only be 1 otherwise
    errCode = err_tup

这将在不更改生成元组的其余代码的情况下工作,并且在语义上是清晰的。在

基于“简单比复杂好。”

相关问题 更多 >