原文链接: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)
相关阅读:
如果本文还没有完全解决你的疑惑,你也可以在微信公众号“桔子code”后台给我留言,欢迎一起探讨交流。