# HG changeset patch # User Paul Boddie # Date 1491179086 -7200 # Node ID 6097bc0ef5ec4e08adf70187afd5ae79721c9860 # Parent 88933212404b336de295219755231c9799a9b405 Added initial support for string formatting. diff -r 88933212404b -r 6097bc0ef5ec lib/__builtins__/str.py --- a/lib/__builtins__/str.py Mon Apr 03 01:37:06 2017 +0200 +++ b/lib/__builtins__/str.py Mon Apr 03 02:24:46 2017 +0200 @@ -22,7 +22,8 @@ from __builtins__.operator import _negate from __builtins__.sequence import hashable, itemaccess from __builtins__.types import check_int -from native import str_add, str_lt, str_gt, str_eq, str_ord, \ +from native import isinstance as _isinstance, \ + str_add, str_lt, str_gt, str_eq, str_ord, \ str_substr WHITESPACE = (" ", "\f", "\n", "\r", "\t") @@ -209,7 +210,47 @@ return self._binary_op_rev(str_add, other, True) - def __mod__(self, other): pass + def __mod__(self, other): + + "Format 'other' using this string." + + if not _isinstance(other, tuple): + other = [other] + + i = 0 + first = True + b = buffer() + + for s in self.split("%"): + if first: + b.append(s) + first = False + continue + + # Handle format codes. + # NOTE: To be completed. + + if s.startswith("%"): + b.append(s) + + elif s.startswith("s"): + b.append(str(other[i])) + b.append(s[1:]) + i += 1 + + elif s.startswith("r"): + b.append(repr(other[i])) + b.append(s[1:]) + i += 1 + + # Unrecognised code: probably just a stray %. + + else: + b.append("%") + b.append(s) + + return str(b) + def __rmod__(self, other): pass def __mul__(self, other): diff -r 88933212404b -r 6097bc0ef5ec tests/string.py --- a/tests/string.py Mon Apr 03 01:37:06 2017 +0200 +++ b/tests/string.py Mon Apr 03 02:24:46 2017 +0200 @@ -100,6 +100,8 @@ print s7.split(maxsplit=2) # ["Hello...", "world,", "planet,\n globe."] print s7.split("\n") # ["Hello...", " world,", " planet,", " globe."] +print "RGB(%r, %r, %r)".split("%") # ["RGB(", "r, ", "r, ", "r)"] + # NOTE: To test rsplit once list.insert is implemented. # Test stripping of strings. @@ -117,3 +119,7 @@ # Test quoting of strings. print repr('æ\nø\rå\t"') # "\xe6\n\xf8\r\xe5\t\"" + +# Test formatting of strings. + +print "RGB(%r, %r, %r)" % (1, 2, 3)