Skip to content

String formatting clarification #95088

@FrankMillman

Description

@FrankMillman

https://docs.python.org/3/library/string.html#formatstrings has the following -

An expression of the form '.name' selects the named attribute using [getattr()], while an expression of the form '[index]' does an index lookup using __getitem__().

An expression of the form [1] correctly returns the element in position 1. An expression of the form [-1] fails with TypeError: list indices must be integers or slices, not str.

Discussion on python-list (https://mail.python.org/pipermail/python-list/2022-July/906930.html) led to unearthing this quote from PEP3101 - Advanced String Formatting (https://peps.python.org/pep-3101/#simple-and-compound-field-names) -

The rules for parsing an item key are very simple. If it starts with a digit, then it is treated as a number, otherwise it is used as a string.

It was felt that the documentation would be improved if this rule was made explicit.

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    docsDocumentation in the Doc dir

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions