Skip to content

Commit

Permalink
implement string slicing for format strings
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
mikf committed Jul 14, 2018
1 parent 269dc2b commit 8fe9056
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
4 changes: 4 additions & 0 deletions gallery_dl/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,10 @@ def get_field(self, field_name, kwargs):
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]

Expand Down
10 changes: 10 additions & 0 deletions test/test_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,16 @@ def test_missing_custom_default(self):
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)
Expand Down

0 comments on commit 8fe9056

Please sign in to comment.