Skip to content

Instantly share code, notes, and snippets.

@b-adams
Forked from anonymous/Visualize where Python slicing happens
Last active January 20, 2017 14:22
Show Gist options
  • Save b-adams/8830f055a6f169cf57430d88e72ae342 to your computer and use it in GitHub Desktop.
Save b-adams/8830f055a6f169cf57430d88e72ae342 to your computer and use it in GitHub Desktop.
Visualize where Python slicing happens
def show_slicing(text, start=0, stop=None, step=1):
if step<1:
print("Sorry, reverse stepping not supported in this visualization")
else:
sliced_text = text[start:stop:step]
lead_space = ' '*start+'|'
marker = '^' + (step-1)*' '
(marks, tail) = divmod(len(text)-start, step)
untruncated_markline = lead_space + marker*marks + 'x'*tail
truncated_markline = untruncated_markline[:(stop+1)]+'|'
print(f'\nSlicing start={start} stop={stop} step={step}')
print(f'|{text}|')
print(f'{truncated_markline}')
print(f'Slicing result: <{sliced_text}>')
show_slicing('The quick brown fox jumped over the lazy sleeping dog',1,-5,4)
show_slicing('The quick brown fox jumped over the lazy sleeping dog',2,13,3)
show_slicing('The quick brown fox jumped over the lazy sleeping dog',2,13,3)
show_slicing('The quick brown fox jumped over the lazy sleeping dog',2,14,3)
show_slicing('The quick brown fox jumped over the lazy sleeping dog',2,15,3)
show_slicing('The quick brown fox jumped over the lazy sleeping dog',10,13)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment