我的这本字典包含Error_ID
和Error_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
答案 0 :(得分:2)
您可以使用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'))