Python错误集锦:格式化字符串IndexError: Replacement index 5 out of range for positional args tuple

原文链接:http://www.juzicode.com/archives/2725

错误提示:

格式化字符串时提示index超出范围:IndexError: Replacement index 5 out of range for positional args tuple

#juzicode.com/vx:桔子code
a = 3
b = 5.12345
c = '桔子code'
d = [1,2,3,4,5]
e = (1,2,3,4,5)
f = {1,2,3,4,5}

out = 'a:{0},b:{1},c:{2},d:{3},e:{4},f:{5}'.format(a,b,c,d,e)
print('字符串转换后',out)  
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-25-0231cedbc123> in <module>
      7 f = {1,2,3,4,5}
      8 
----> 9 out = 'a:{0},b:{1},c:{2},d:{3},e:{4},f:{5}'.format(a,b,c,d,e)
     10 print('字符串转换后',out)

IndexError: Replacement index 5 out of range for positional args tuple

错误原因:

1、格式化方法提供了0~5的6个占位符,但是format()内只有5个变量。

解决方法:

1、增加占位符为5的变量,在format()中增加变量f:

#juzicode.com/vx:桔子code
a = 3
b = 5.12345
c = '桔子code'
d = [1,2,3,4,5]
e = (1,2,3,4,5)
f = {1,2,3,4,5}

out = 'a:{0},b:{1},c:{2},d:{3},e:{4},f:{5}'.format(a,b,c,d,e,f)
print('字符串转换后',out)  

相关阅读:

  1. Python基础教程2c–数据类型-list(列表)
  2. Python基础教程2d–数据类型-tuple(元组)


关注微信公众号:“桔子code”,欢迎后台留言撩我,我会尽我所能为你解惑Python,C等编程知识

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注