Skip to content

Instantly share code, notes, and snippets.

@telamonian
Created September 30, 2020 04:24
Show Gist options
  • Save telamonian/c13f656c9e74b026e797b476505f3f98 to your computer and use it in GitHub Desktop.
Save telamonian/c13f656c9e74b026e797b476505f3f98 to your computer and use it in GitHub Desktop.
parse string into numpy-style slice object

My problem: jupyterlab/jupyterlab-hdf5#4

I realllllly want to avoid having to write my own parser for this. Here's my best (very hacky) attempt so far:

# adapted from https://stackoverflow.com/a/43090200/425458

def parseSlice(sliceStr):
    return tuple((slice(*(int(i) if i else None for i in part.strip().split(':'))) if ':' in part else int(part.strip())) for part in sliceStr.split(','))

which can then do stuff like:

>>> list(parseSlice("0, 1:2, :2, 12"))

[0, slice(1, 2, None), slice(None, 2, None), 12]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment