Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

str.format(list) with negative index doesn't work in Python

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
like image 956
Explogit Avatar asked Oct 25 '09 07:10

Explogit


People also ask

Can Python list have negative index?

To recap, Python supports positive zero-based indexing and negative indexing that starts from -1. Negative indexing in Python means the indexing starts from the end of the iterable.

Does Python support negative indexing in string?

If an index number in a slice is out of bounds, it is ignored and the slice uses the start or end of the string. Negative Index As an alternative, Python supports using negative numbers to index into a string: -1 means the last char, -2 is the next to last, and so on.

How do you format a negative number in Python?

Only negative numbers are prefixed with a sign by default. You can change this by specifying the sign format option. When you use ' ' (space) for sign option, it displays a leading space for positive numbers and a minus sign for negative numbers.

What is negative indexing string in Python?

Negative Indexing in Python Negative indexing accesses items relative to the end of the sequence. The index -1 reads the last element, -2 the second last, and so on. For example, let's read the last and the second last number from a list of numbers: nums = [1, 2, 3, 4] last = nums[-1]


1 Answers

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:-(.

like image 142
Alex Martelli Avatar answered Nov 15 '22 19:11

Alex Martelli