Exp*_*git 9 python string formatting
我在替换字段中使用负索引来输出格式化列表,但它引发了一个TypeError.代码如下:
>>> 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
Ale*_*lli 13
这就是格式字符串规范中我称之为设计故障的内容.根据文档,
element_index ::= integer | index_string
Run Code Online (Sandbox Code Playgroud)
但是,唉,-1
不是"整数" - 它是一个表达.一元 - 负运算符甚至没有特别高的优先级,因此例如print(-2**2)
发出-4
- 另一个常见问题,可以说是设计故障(**
运营商具有更高的优先级,因此首先发生上电,然后是变更 -优先级较低的一元要求的标志-
).
格式字符串中该位置中不是整数(但是,例如,表达式)的任何内容都被视为字符串,以索引dict参数 - 例如:
$ python3 -c "print('The last:{0[2+2]}'.format({'2+2': 23}))"
The last:23
Run Code Online (Sandbox Code Playgroud)
不确定这是否值得在Python trac中引发一个问题,但它肯定是一个有点令人惊讶的行为:-(.
归档时间: |
|
查看次数: |
1744 次 |
最近记录: |