diff options
Diffstat (limited to 'Lib')
-rwxr-xr-x | Lib/UserString.py | 1 | ||||
-rw-r--r-- | Lib/string.py | 14 | ||||
-rw-r--r-- | Lib/test/string_tests.py | 10 | ||||
-rw-r--r-- | Lib/test/test_unicode.py | 14 |
4 files changed, 29 insertions, 10 deletions
diff --git a/Lib/UserString.py b/Lib/UserString.py index f4f5cab..292e852 100755 --- a/Lib/UserString.py +++ b/Lib/UserString.py @@ -128,6 +128,7 @@ class UserString: def translate(self, *args): return self.__class__(self.data.translate(*args)) def upper(self): return self.__class__(self.data.upper()) + def zfill(self, width): return self.__class__(self.data.zfill(width)) class MutableString(UserString): """mutable string objects diff --git a/Lib/string.py b/Lib/string.py index d68b0bf..cd9909e 100644 --- a/Lib/string.py +++ b/Lib/string.py @@ -190,7 +190,10 @@ def rfind(s, *args): _float = float _int = int _long = long -_StringTypes = (str, unicode) +try: + _StringTypes = (str, unicode) +except NameError: + _StringTypes = (str,) # Convert string to float def atof(s): @@ -277,13 +280,8 @@ def zfill(x, width): """ if not isinstance(x, _StringTypes): - x = str(x) - n = len(x) - if n >= width: return x - sign = '' - if x[0] in '-+': - sign, x = x[0], x[1:] - return sign + '0'*(width-n) + x + x = repr(x) + return x.zfill(width) # Expand tabs in a string. # Doesn't take non-printing chars into account, but does understand \n. diff --git a/Lib/test/string_tests.py b/Lib/test/string_tests.py index 5c8dd93..ea25983 100644 --- a/Lib/test/string_tests.py +++ b/Lib/test/string_tests.py @@ -227,6 +227,16 @@ def run_method_tests(test): test('endswith', 'ab', 0, 'ab', 0, 1) test('endswith', 'ab', 0, 'ab', 0, 0) + test('zfill', '123', '123', 2) + test('zfill', '123', '123', 3) + test('zfill', '123', '0123', 4) + test('zfill', '+123', '+123', 3) + test('zfill', '+123', '+123', 4) + test('zfill', '+123', '+0123', 5) + test('zfill', '-123', '-123', 3) + test('zfill', '-123', '-123', 4) + test('zfill', '-123', '-0123', 5) + test('zfill', '', '000', 3) test('zfill', '34', '34', 1) test('zfill', '34', '0034', 4) diff --git a/Lib/test/test_unicode.py b/Lib/test/test_unicode.py index 4b77e75..29dd819 100644 --- a/Lib/test/test_unicode.py +++ b/Lib/test/test_unicode.py @@ -206,8 +206,18 @@ if 0: test('capwords', u'abc\tdef\nghi', u'Abc Def Ghi') test('capwords', u'abc\t def \nghi', u'Abc Def Ghi') -verify(string.zfill(u'34', 1) == u'34') -verify(string.zfill(u'34', 5) == u'00034') +test('zfill', u'123', u'123', 2) +test('zfill', u'123', u'123', 3) +test('zfill', u'123', u'0123', 4) +test('zfill', u'+123', u'+123', 3) +test('zfill', u'+123', u'+123', 4) +test('zfill', u'+123', u'+0123', 5) +test('zfill', u'-123', u'-123', 3) +test('zfill', u'-123', u'-123', 4) +test('zfill', u'-123', u'-0123', 5) +test('zfill', u'', u'000', 3) +test('zfill', u'34', u'34', 1) +test('zfill', u'34', u'00034', 5) # Comparisons: print 'Testing Unicode comparisons...', |