python-3.x - .format 中的元组索引超出范围
问题描述
我有两个要打印的论点
print('{0:25}${2:>5.2f}'.format('object', 20))
但他们给出了以下回应:
Traceback (most recent call last):
IndexError: tuple index out of range
但是当我将代码更改为以下内容时,我得到了所需的输出:
print('{0:25}${2:>5.2f}'.format('object', 20, 20))
我不明白为什么,因为我只有两组 {}。谢谢
解决方案
您的问题是 $ 符号后的 2 索引:
print('{0:25}${2:>5.2f}'.format('object', 20, 20))
当您在 python 中的字符串上使用 .format 时,数字 at{number:}
是您想要的参数的索引。例如以下:
"hello there {1:} i want you to give me {0:} dollars".format(2,"Tom")
将导致以下输出:
'hello there Tom i want you to give me 2 dollars'
这里有一个简单的例子: https ://www.programiz.com/python-programming/methods/string/format
总而言之,为了让您的代码正常工作,只需使用:
print('{0:25}${1:>5.2f}'.format('object', 20))
推荐阅读
- default - 如何在 WordPress 音频播放器中将默认音量设置为 100%?
- lotusscript - 根据文本值命名数组
- javascript - 将数组值添加到引导表
- java - 使用 XSLT 从 JSON 生成 PDF - 页眉和页脚内容应与表格一起显示在所有页面中
- java - 解释我的计算机如何读取我的河内塔代码
- javascript - 如何将javascript与具有相同ID的多个elememts一起使用?
- java - 通过长链元素从适配器到活动的侦听器
- html - 我们应该为文章的标签使用哪个 HTML 属性?
- javascript - 如果满足条件,则停止 Javascript 点击事件执行
- asynchronous - Vuetify 滚动问题