mirror of
https://github.com/pocketpy/pocketpy
synced 2026-08-05 05:37:10 +08:00
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:
parent
f2b6d90a72
commit
005550e92a
@ -447,6 +447,12 @@ static bool str_zfill(int argc, py_Ref argv) {
|
||||
}
|
||||
c11_sbuf 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++) {
|
||||
c11_sbuf__write_char(&buf, '0');
|
||||
}
|
||||
|
||||
@ -112,6 +112,9 @@ assert s2.join( seq ) == "runoob"
|
||||
|
||||
assert 'x'.zfill(5) == '0000x'
|
||||
assert '568'.zfill(1) == '568'
|
||||
assert '-5'.zfill(4) == '-005'
|
||||
assert '+5'.zfill(4) == '+005'
|
||||
assert '-'.zfill(3) == '-00'
|
||||
|
||||
num = 6
|
||||
assert str(num) == '6'
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user