소스 검색

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.
Md Kaif 2 달 전
부모
커밋
005550e92a
2개의 변경된 파일과 9개의 추가작업 그리고 0개의 파일을 삭제
  1. 6 0
      src/bindings/py_str.c
  2. 3 0
      tests/041_str.py

+ 6 - 0
src/bindings/py_str.c

@@ -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');
     }
     }

+ 3 - 0
tests/041_str.py

@@ -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'