I have a slice
object, and I'd like to print it out in the form of a string start:stop:step
. How do I do so?
There's nothing built-in to do this, as far as I know, but we can easily write some code to do it using the values from the slice object, per the docs:
Slice objects have read-only data attributes
start
,stop
, andstep
which merely return the argument values (or their default).
def slice_to_str(s: slice) -> str:
return f'{s.start!r}:{s.stop!r}:{s.step!r}'
For example:
>>> print(slice_to_str(slice(15, 95, 5)))
15:95:5
>>> print(slice_to_str(slice(60)))
None:60:None
None
sYou can use ... is not None else ''
def slice_to_str(s: slice) -> str:
start, stop, step = [
(repr(val) if val is not None else '')
for val in [s.start, s.stop, s.step]]
return f'{start}:{stop}:{step}'
For example:
>>> print(slice_to_str(slice(60)))
:60:
>>> print(slice_to_str(slice(None)))
::
>>> print(slice_to_str(slice(None, None, 2)))
::2
>>> print(slice_to_str(slice('h', 't')))
'h':'t':
None
Just add a check for it: if s.step is None ...
def slice_to_str(s: slice) -> str:
start, stop, step = [
(repr(val) if val is not None else '')
for val in [s.start, s.stop, s.step]]
step_optional = f':{step}' if s.step is not None else ''
return f'{start}:{stop}{step_optional}'
For example:
>>> print(slice_to_str(slice(60)))
:60
>>> print(slice_to_str(slice(None)))
:
>>> print(slice_to_str(slice(None, None, 2)))
::2