[pypy-dev] pow and complex object

Ben Young ben at transversal.com
Mon Jul 5 11:40:18 CEST 2004


On Monday 05 July 2004 10:28, holger krekel wrote:
> [Ben Young Mon, Jul 05, 2004 at 09:27:45AM +0100]
>
> > Hi, I have a patch for string formatting where you want to left pad with
> > zeros. Could someone apply it for me if it looks reasonable?
>
> can you write a test or two for this?
>

Ok, here is the revised patch. (+ a bug fix :) Must remember to write tests 
first!

Ben

Index: objspace/std/stringobject.py
===================================================================
--- objspace/std/stringobject.py        (revision 5431)
+++ objspace/std/stringobject.py        (working copy)
@@ -991,9 +991,16 @@
             else:
                 width = None
                 prec = None
+                lpadchar = ' '
+                padzeros = False
+                seennum = False
                 if c in '-0123456789':
                     j = i
                     while format[j] in '-0123456789':
+                        if format[j] in '0123456789' and not seennum:
+                            seennum = True
+                            if format[j] == '0':
+                                padzeros = True
                         j += 1
                     if format[i:j] != '-':
                         width = int(format[i:j])
@@ -1050,6 +1057,10 @@
                 else:
                     raise ValueError, "unsupported format character '%s' (%x) 
at index %d" % (
                             c, ord(c), i)
+
+                if c in 'xdg' and padzeros:
+                    lpadchar = '0'
+
                 if prec is not None:
                     pieces[-1] = pieces[-1][:prec]
                 if width is not None:
@@ -1059,7 +1070,7 @@
                         p = p + ' '*d
                     else:
                         d = max(width - len(p), 0)
-                        p = ' '*d + p
+                        p = lpadchar*d + p
                     pieces[-1] = p
             state = 0
             start = i+1
Index: objspace/std/test/test_stringformat.py
===================================================================
--- objspace/std/test/test_stringformat.py      (revision 5431)
+++ objspace/std/test/test_stringformat.py      (working copy)
@@ -105,6 +105,14 @@
         self.assertEquals("%-5.3s"%'a',     'a    ')
         self.assertEquals("%-5.3s"%'abcde', 'abc  ')

+    def test_zero_pad(self):
+        self.assertEquals("%02d"%1,   "01")
+        self.assertEquals("%05d"%1,   "00001")
+        self.assertEquals("%-05d"%1,  "1    ")
+        self.assertEquals("%04f"%2.3, "2.300000")
+        self.assertEquals("%04g"%2.3, "02.3")
+        self.assertEquals("%-04g"%2.3,"2.3 ")
+        self.assertEquals("%04s"%2.3, " 2.3")

 if __name__ == '__main__':
     testit.main()





More information about the Pypy-dev mailing list