我的字典具有Error_IDError_Messages映射,并且这些错误消息具有{},因此在打印时它们可以具有动态数据

dict = {'101': 'Invalid table name {}', '102': 'Invalid pair {} and {}'}


我有这个函数,每次遇到错误都会调用

def print_error(error_id,error_data)
        print(error_id,dict[error_id].format("sample_table")

error_id='101'

print(error_id,dict[error_id].format("sample_table"))
Invalid table name sample_table


但是对于第二个错误,我应该怎么做,这样我就可以在print_error模块中通过单个print语句传递两件事,以使输出类似于

102 Invalid pair Sample_pair1 and Sample_pair2

最佳答案

您可以使用python的可迭代解包功能将可变数量的参数传递给str.format

def print_error(error_id,error_data):
    if not isinstance(error_data, tuple): # if error_data isn't a tuple
        error_data= (error_data,) # make it a tuple so we can unpack it
    print(error_id,dict[error_id].format(*error_data)) # unpack the tuple

print_error('101',"sample_table")
print_error('102',('a','b'))

关于python - 访问数据框并打印自定义错误消息,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38607202/

10-09 05:38
查看更多