[pypy-svn] r5085 - in pypy/trunk/src/pypy/objspace/std: . test
mwh at codespeak.net
mwh at codespeak.net
Sun Jun 13 17:33:14 CEST 2004
Author: mwh
Date: Sun Jun 13 17:33:13 2004
New Revision: 5085
Modified:
pypy/trunk/src/pypy/objspace/std/stringobject.py
pypy/trunk/src/pypy/objspace/std/test/test_stringformat.py
Log:
Courtesy of wireless internet at Copenhagen, a first cut at field widths
and precision in string formatting. Still more to do, but enough to get
dis-goal.py working (only 500 times slower than CPython!)
Modified: pypy/trunk/src/pypy/objspace/std/stringobject.py
==============================================================================
--- pypy/trunk/src/pypy/objspace/std/stringobject.py (original)
+++ pypy/trunk/src/pypy/objspace/std/stringobject.py Sun Jun 13 17:33:13 2004
@@ -986,6 +986,25 @@
if c=='%':
pieces.append('%')
else:
+ width = None
+ prec = None
+ if c in '-0123456789':
+ j = i
+ while format[j] in '-0123456789':
+ j += 1
+ if format[i:j] != '-':
+ width = int(format[i:j])
+ i = j
+ c = format[j]
+ if c == '.':
+ i += 1
+ j = i
+ while format[j] in '0123456789':
+ j += 1
+ prec = int(format[i:j])
+ i = j
+ c = format[j]
+
if c == '(':
# read name
j = format.find(')', i+1)
@@ -1028,6 +1047,17 @@
else:
raise ValueError, "unsupported format character '%s' (%x) at index %d" % (
c, ord(c), i)
+ if prec is not None:
+ pieces[-1] = pieces[-1][:prec]
+ if width is not None:
+ p = pieces[-1]
+ if width < 0:
+ d = max(-width - len(p), 0)
+ p = p + ' '*d
+ else:
+ d = max(width - len(p), 0)
+ p = ' '*d + p
+ pieces[-1] = p
state = 0
start = i+1
i += 1
Modified: pypy/trunk/src/pypy/objspace/std/test/test_stringformat.py
==============================================================================
--- pypy/trunk/src/pypy/objspace/std/test/test_stringformat.py (original)
+++ pypy/trunk/src/pypy/objspace/std/test/test_stringformat.py Sun Jun 13 17:33:13 2004
@@ -87,5 +87,24 @@
def test_format_wrong_char(self):
self.assertRaises(ValueError, 'a%Zb'.__mod__, ((23,),))
+class TestWidthPrec(testit.AppTestCase):
+ def setUp(self):
+ self.space = testit.objspace()
+
+ def test_width(self):
+ self.assertEquals("%3s"%'a', ' a')
+ self.assertEquals("%-3s"%'a', 'a ')
+
+ def test_prec_string(self):
+ self.assertEquals("%.3s"%'a', 'a')
+ self.assertEquals("%.3s"%'abcde', 'abc')
+
+ def test_prec_width_string(self):
+ self.assertEquals("%5.3s"%'a', ' a')
+ self.assertEquals("%5.3s"%'abcde', ' abc')
+ self.assertEquals("%-5.3s"%'a', 'a ')
+ self.assertEquals("%-5.3s"%'abcde', 'abc ')
+
+
if __name__ == '__main__':
testit.main()
More information about the Pypy-commit
mailing list