implement string slicing for format strings

It is now possible to slice string (or list) values of format string
replacement fields with the same syntax as in regular Python code.

"{digits}"       -> "0123456789"
"{digits[2:-2]}" -> "234567"
"{digits[:5]}"   -> "01234"

The optional third parameter (step) has been left out to simplify things.
This commit is contained in:
Mike Fährmann
2018-07-13 16:52:56 +02:00
parent 269dc2bbd5
commit 8fe9056b16
2 changed files with 14 additions and 0 deletions

View File

@@ -200,6 +200,16 @@ class TestFormatter(unittest.TestCase):
self._run_test("{missing[key]}", replacement, default)
self._run_test("{missing:?a//}", "a" + default, default)
def test_slicing(self):
v = self.kwdict["a"]
self._run_test("{a[1:10]}" , v[1:10])
self._run_test("{a[-10:-1]}", v[-10:-1])
self._run_test("{a[5:]}" , v[5:])
self._run_test("{a[50:]}", v[50:])
self._run_test("{a[:5]}" , v[:5])
self._run_test("{a[:50]}", v[:50])
self._run_test("{a[:]}" , v)
def _run_test(self, format_string, result, default=None):
formatter = util.Formatter(default)
output = formatter.vformat(format_string, self.kwdict)