原文链接: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)  
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐