fix(str): zfill should preserve a leading sign (#533)

zfill writes the padding zeros before the whole string, so a leading
+ or - ends up in the middle of the result instead of staying in front.
For example "-5".zfill(4) gave '00-5' where CPython gives '-005'.

CPython inserts the padding after the sign character, and the sign
counts toward the requested width. Write the sign first, then the
zeros, then the rest of the string. delta is still computed before
this, so the total length is unchanged.

The existing tests only covered unsigned strings, which is why this
went unnoticed. Added three asserts alongside them.
This commit is contained in:
Md Kaif 2026-07-21 16:39:11 +05:30 committed by GitHub
parent f2b6d90a72
commit 005550e92a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 9 additions and 0 deletions

View File

@ -447,6 +447,12 @@ static bool str_zfill(int argc, py_Ref argv) {
} }
c11_sbuf buf; c11_sbuf buf;
c11_sbuf__ctor(&buf); c11_sbuf__ctor(&buf);
// a leading sign is kept in front; the padding goes after it
if(self.size > 0 && (self.data[0] == '+' || self.data[0] == '-')) {
c11_sbuf__write_char(&buf, self.data[0]);
self.data++;
self.size--;
}
for(int i = 0; i < delta; i++) { for(int i = 0; i < delta; i++) {
c11_sbuf__write_char(&buf, '0'); c11_sbuf__write_char(&buf, '0');
} }

View File

@ -112,6 +112,9 @@ assert s2.join( seq ) == "runoob"
assert 'x'.zfill(5) == '0000x' assert 'x'.zfill(5) == '0000x'
assert '568'.zfill(1) == '568' assert '568'.zfill(1) == '568'
assert '-5'.zfill(4) == '-005'
assert '+5'.zfill(4) == '+005'
assert '-'.zfill(3) == '-00'
num = 6 num = 6
assert str(num) == '6' assert str(num) == '6'