带有负向索引的str.format(list)在Python中不起作用 [英] str.format(list) with negative index doesn't work in Python

查看:297
本文介绍了带有负向索引的str.format(list)在Python中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 $ b $在替换字段中使用一个负索引来输出一个格式化的列表,但是它引发了一个TypeError。 b >>> a = [1,2,3] 
>>> a [2]
3
>>> a [-1]
3
>>>'最后一个:{0 [2]}'。格式(a)
'最后一个:3'
>>>'最后一个:{0 [-1]}'。 (a)
Traceback(最近一次调用的最后一个):

中的第1行FileError:列表索引必须是整数而不是str
解决方案

这是我所谓的格式字符串规格设计故障。根据文档

  element_index :: = integer | index_string 

但是,唉, -1 是不是一个整数 - 这是一个表达式。一元减运算符甚至没有特别高的优先级,所以例如 print(-2 ** 2)发出 -4 - 另一个常见的问题,可以说是一个设计故障( ** 运算符具有更高的优先级,所以提高权力首先发生,然后改变-sign由低优先级的一元请求 - )。



格式字符串中那些不是整数(但是,例如,一个表达式)被视为一个字符串来索引一个dict参数 - 例如:

pre $ $ python3 -cprint('last:{0 [2 + 2]}'。format({'2 + 2':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中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆