为什么"断言211 == 211"失败?

时间:2016-12-02 14:39:49

标签: python string-formatting

这失败了:

train_data = pd.concat([train_cancelled, train_not_cancelled]).as_matrix()

mat_col_size = int((num_days * 3) + 1)

assert isinstance(mat_col_size, int), "mat_col_size is not an int"
assert isinstance(train_data.shape[1], int), "train_data.shape[1] is not an int"

assert train_data.shape[1] == mat_col_size, \
    "Number of columns in train data must be 'num_fetaures + 1 = {0:d}' (label) but is '{0:1}'." \
        .format(mat_col_size, train_data.shape[1])

它将打印:

AssertionError: Number of columns in train data must be 'num_fetaures + 1 = 211' (label) but is '211'.

我的问题是:有多少不同的事情可能出错并导致此失败,因为我根本找不到问题或我的代码没有成为第三个assert的原因!

1 个答案:

答案 0 :(得分:6)

您的格式字符串通过使用位置选择器0两次选择第一个参数两次。您实际上没有看到train_data.shape[1]的值,它在两种情况下都会打印mat_col_size的值。我想你的意思是:

"Number of columns in train data must be 'num_fetaures + 1 = {0:d}' (label) but is '{1}'."

或者,假设它是Py 2.7+,你可以简化为:

"Number of columns in train data must be 'num_fetaures + 1 = {}' (label) but is '{}'."

允许它自动将占位符与位置参数匹配而不明确指定数字(并且没有理由指定d格式单位;它不是printf,它是&#39 ; ll stringify自己)。