Skip to content

Commit 133013e

Browse files
bpo-28146: Fix a confusing error message in str.format() (GH-24213)
Automerge-Triggered-By: GH:pitrou (cherry picked from commit 4aeee0b) Co-authored-by: Irit Katriel <[email protected]>
1 parent 04c4610 commit 133013e

File tree

3 files changed

+14
-4
lines changed

3 files changed

+14
-4
lines changed

Lib/test/test_unicode.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1217,8 +1217,11 @@ def __repr__(self):
12171217
0, 1, 2, 3, 4, 5, 6, 7)
12181218

12191219
# string format spec errors
1220-
self.assertRaises(ValueError, "{0:-s}".format, '')
1221-
self.assertRaises(ValueError, format, "", "-")
1220+
sign_msg = "Sign not allowed in string format specifier"
1221+
self.assertRaisesRegex(ValueError, sign_msg, "{0:-s}".format, '')
1222+
self.assertRaisesRegex(ValueError, sign_msg, format, "", "-")
1223+
space_msg = "Space not allowed in string format specifier"
1224+
self.assertRaisesRegex(ValueError, space_msg, "{: }".format, '')
12221225
self.assertRaises(ValueError, "{0:=s}".format, '')
12231226

12241227
# Alternate formatting is not supported
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix a confusing error message in :func:`str.format`.

Python/formatter_unicode.c

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -773,8 +773,14 @@ format_string_internal(PyObject *value, const InternalFormatSpec *format,
773773

774774
/* sign is not allowed on strings */
775775
if (format->sign != '\0') {
776-
PyErr_SetString(PyExc_ValueError,
777-
"Sign not allowed in string format specifier");
776+
if (format->sign == ' ') {
777+
PyErr_SetString(PyExc_ValueError,
778+
"Space not allowed in string format specifier");
779+
}
780+
else {
781+
PyErr_SetString(PyExc_ValueError,
782+
"Sign not allowed in string format specifier");
783+
}
778784
goto done;
779785
}
780786

0 commit comments

Comments
 (0)