diff --git a/Lib/test/test_str.py b/Lib/test/test_str.py index 6600dcf9157971..e5a2b0faa9b3c0 100644 --- a/Lib/test/test_str.py +++ b/Lib/test/test_str.py @@ -1388,6 +1388,11 @@ def __repr__(self): self.assertEqual("{!s}".format(n), 'N(data)') self.assertRaises(TypeError, "{}".format, n) + # String index for sequences + 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') diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2024-09-24-11-12-09.gh-issue-124294.jBPOm1.rst b/Misc/NEWS.d/next/Core_and_Builtins/2024-09-24-11-12-09.gh-issue-124294.jBPOm1.rst new file mode 100644 index 00000000000000..aa0839167fc08b --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2024-09-24-11-12-09.gh-issue-124294.jBPOm1.rst @@ -0,0 +1,2 @@ +More informative error message in :func:`str.format` when passing negative +integer or string index to sequence. diff --git a/Objects/stringlib/unicode_format.h b/Objects/stringlib/unicode_format.h index 91c71ab5736c25..10e1f4f2df52d6 100644 --- a/Objects/stringlib/unicode_format.h +++ b/Objects/stringlib/unicode_format.h @@ -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);