1.1 --- a/lib/__builtins__/str.py Mon Apr 03 01:37:06 2017 +0200
1.2 +++ b/lib/__builtins__/str.py Mon Apr 03 02:24:46 2017 +0200
1.3 @@ -22,7 +22,8 @@
1.4 from __builtins__.operator import _negate
1.5 from __builtins__.sequence import hashable, itemaccess
1.6 from __builtins__.types import check_int
1.7 -from native import str_add, str_lt, str_gt, str_eq, str_ord, \
1.8 +from native import isinstance as _isinstance, \
1.9 + str_add, str_lt, str_gt, str_eq, str_ord, \
1.10 str_substr
1.11
1.12 WHITESPACE = (" ", "\f", "\n", "\r", "\t")
1.13 @@ -209,7 +210,47 @@
1.14
1.15 return self._binary_op_rev(str_add, other, True)
1.16
1.17 - def __mod__(self, other): pass
1.18 + def __mod__(self, other):
1.19 +
1.20 + "Format 'other' using this string."
1.21 +
1.22 + if not _isinstance(other, tuple):
1.23 + other = [other]
1.24 +
1.25 + i = 0
1.26 + first = True
1.27 + b = buffer()
1.28 +
1.29 + for s in self.split("%"):
1.30 + if first:
1.31 + b.append(s)
1.32 + first = False
1.33 + continue
1.34 +
1.35 + # Handle format codes.
1.36 + # NOTE: To be completed.
1.37 +
1.38 + if s.startswith("%"):
1.39 + b.append(s)
1.40 +
1.41 + elif s.startswith("s"):
1.42 + b.append(str(other[i]))
1.43 + b.append(s[1:])
1.44 + i += 1
1.45 +
1.46 + elif s.startswith("r"):
1.47 + b.append(repr(other[i]))
1.48 + b.append(s[1:])
1.49 + i += 1
1.50 +
1.51 + # Unrecognised code: probably just a stray %.
1.52 +
1.53 + else:
1.54 + b.append("%")
1.55 + b.append(s)
1.56 +
1.57 + return str(b)
1.58 +
1.59 def __rmod__(self, other): pass
1.60
1.61 def __mul__(self, other):
2.1 --- a/tests/string.py Mon Apr 03 01:37:06 2017 +0200
2.2 +++ b/tests/string.py Mon Apr 03 02:24:46 2017 +0200
2.3 @@ -100,6 +100,8 @@
2.4 print s7.split(maxsplit=2) # ["Hello...", "world,", "planet,\n globe."]
2.5 print s7.split("\n") # ["Hello...", " world,", " planet,", " globe."]
2.6
2.7 +print "RGB(%r, %r, %r)".split("%") # ["RGB(", "r, ", "r, ", "r)"]
2.8 +
2.9 # NOTE: To test rsplit once list.insert is implemented.
2.10
2.11 # Test stripping of strings.
2.12 @@ -117,3 +119,7 @@
2.13 # Test quoting of strings.
2.14
2.15 print repr('æ\nø\rå\t"') # "\xe6\n\xf8\r\xe5\t\""
2.16 +
2.17 +# Test formatting of strings.
2.18 +
2.19 +print "RGB(%r, %r, %r)" % (1, 2, 3)