str.format(list) with negative index doesn#39;t work in Python(带有负索引的 str.format(list) 在 Python 中不起作用)
问题描述
我在替换字段中使用负索引输出格式化列表,但它引发了一个TypeError.代码如下:
<上一页>>>> a=[1,2,3]>>> 一个[2]3>>> 一个[-1]3>>> '最后一个:{0[2]}'.format(a)'最后一个:3'>>> '最后一个:{0[-1]}'.format(a)回溯(最近一次通话最后):文件",第 1 行,在TypeError:列表索引必须是整数,而不是 str这就是我所说的格式字符串规范中的设计故障.根据 文档,
element_index ::= 整数 |索引字符串但是,唉,-1 不是整数"——它是一个表达式.一元减号运算符甚至没有特别高的优先级,因此例如 print(-2**2) 发出 -4 - 另一个常见问题,可以说一个设计故障(** 操作符具有更高的优先级,因此首先发生升权,然后是较低优先级的一元 - 请求的更改符号).
格式字符串中该位置的任何非整数(但例如表达式)都被视为字符串,以索引 dict 参数 - 例如:
$ python3 -c "print('最后一个:{0[2+2]}'.format({'2+2': 23}))"最后:23不确定这是否值得在 Python trac 中提出问题,但这肯定是一个有点令人惊讶的行为:-(.
I use a negative index in replacement fields to output a formatted list,but it raises a TypeError.The codes are as follows:
>>> a=[1,2,3]
>>> a[2]
3
>>> a[-1]
3
>>> 'The last:{0[2]}'.format(a)
'The last:3'
>>> 'The last:{0[-1]}'.format(a)
Traceback (most recent call last):
File "", line 1, in
TypeError: list indices must be integers, not str
It's what I would call a design glitch in the format string specs. Per the docs,
element_index ::= integer | index_string
but, alas, -1 is not "an integer" -- it's an expression. The unary-minus operator doesn't even have particularly high priority, so that for example print(-2**2) emits -4 -- another common issue and arguably a design glitch (the ** operator has higher priority, so the raise-to-power happens first, then the change-sign requested by the lower priority unary -).
Anything in that position in the format string that's not an integer (but, for example, an expression) is treated as a string, to index a dict argument -- for example:
$ python3 -c "print('The last:{0[2+2]}'.format({'2+2': 23}))"
The last:23
Not sure whether this is worth raising an issue in the Python trac, but it's certainly a somewhat surprising behavior:-(.
这篇关于带有负索引的 str.format(list) 在 Python 中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:带有负索引的 str.format(list) 在 Python 中不起作用
基础教程推荐
- 对多索引数据帧的列进行排序 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
