From 8fe9056b16cbbb14b7e94fa92a8c8369cee654a9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mike=20F=C3=A4hrmann?= Date: Fri, 13 Jul 2018 16:52:56 +0200 Subject: [PATCH] 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. --- gallery_dl/util.py | 4 ++++ test/test_util.py | 10 ++++++++++ 2 files changed, 14 insertions(+) diff --git a/gallery_dl/util.py b/gallery_dl/util.py index ff3eae94..0f700b95 100644 --- a/gallery_dl/util.py +++ b/gallery_dl/util.py @@ -344,6 +344,10 @@ class Formatter(): for is_attr, i in rest: if is_attr: obj = getattr(obj, i) + elif ":" in i: + start, _, stop = i.partition(":") + start = int(start) if start else 0 + return obj[start:int(stop)] if stop else obj[start:] else: obj = obj[i] diff --git a/test/test_util.py b/test/test_util.py index 8333828e..787ec3aa 100644 --- a/test/test_util.py +++ b/test/test_util.py @@ -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)