Skip to content

str.format() raises misleading error when using negative indices #124294

@makukha

Description

@makukha

Bug report

Bug description:

This is a duplicate of #95846. The problem appeared on Stackoverflow, but I didn't manage to reopen the old issue.

>>> x = [1,2,3]
>>> '{x[-1]}'.format(x=x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers or slices, not str
>>> x = (1,2,3)
>>> '{x[-1]}'.format(x=x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: tuple indices must be integers or slices, not str

Expected results:

  • Correct error message: TypeError: ___ indices must be non-negative integers or slices
  • Documentation updated to clearly state that list indices can't be negative.

As long as this issue is not critical, I would be glad to provide PR.

CPython versions tested on:

3.12

Operating systems tested on:

macOS

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    type-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions