Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions Lib/test/test_str.py
Original file line number Diff line number Diff line change
Expand Up @@ -1388,6 +1388,11 @@ def __repr__(self):
self.assertEqual("{!s}".format(n), 'N(data)')
self.assertRaises(TypeError, "{}".format, n)

# String index for sequences
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe you could delete this comment since the user won't see it anyway.

index_msg = 'Index must be a sequence of digits'
self.assertRaisesRegex(TypeError, index_msg, "{[s]}".format, "abc")
self.assertRaisesRegex(TypeError, index_msg, "{[-1]}".format, "abc")

def test_format_map(self):
self.assertEqual(''.format_map({}), '')
self.assertEqual('a'.format_map({}), 'a')
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
More informative error message in :func:`str.format` when passing negative
integer or string index to sequence.
15 changes: 14 additions & 1 deletion Objects/stringlib/unicode_format.h
Original file line number Diff line number Diff line change
Expand Up @@ -462,8 +462,21 @@ get_field_object(SubString *input, PyObject *args, PyObject *kwargs,
tmp = getattr(obj, &name);
else
/* getitem lookup "[]" */
if (index == -1)
if (index == -1) {
if (PySequence_Check(obj)) {
/* string index can't be passed to sequence */
PyObject *str = SubString_new_object(&name);
if (str) {
PyErr_Format(PyExc_TypeError,
"Index must be a sequence of digits, string %R "
"is not allowed",
str);
}
Py_XDECREF(str);
goto error;
}
tmp = getitem_str(obj, &name);
}
else
if (PySequence_Check(obj))
tmp = getitem_sequence(obj, index);
Expand Down
Loading