Skip to content

Instantly share code, notes, and snippets.

@mutaku
Last active December 17, 2015 09:09
Show Gist options
  • Save mutaku/5585477 to your computer and use it in GitHub Desktop.
Save mutaku/5585477 to your computer and use it in GitHub Desktop.
Create a print job string for page range by supplying a total range of pages and an exclude list (such as graphical pages or ones simply not needed).
'''Create a print job string for page range by supplying
a total range of pages and an exclude list (such as graphical
pages or ones simply not needed).
Example:
In [1]: from printer_jobs_strings import make_print_string
In [2]: pages = range(0, 25)
In [3]: exclude = [3, 6, 7, 8, 15, 24]
In [4]: make_print_string(pages, exclude)
Out[5]: '0-2,4-5,9-14,16-23'
'''
def make_print_string(pages, exclude):
# make an inclusion list checking excludes
p = [x for x in pages if x not in exclude]
print_list = list()
for i in range(0, len(p)):
if i == 0:
# first element so we just place it in
print_list.append(p[i])
elif (p[i] - p[i - 1]) > 1:
# we have skipped since last inclusion
# this means we aren't handling end of a range
print_list.append(',')
print_list.append(p[i])
elif (i < len(p) - 1 and (p[i + 1] - p[i]) > 1 or
i == len(p) - 1 and (p[i] - p[i - 1]) == 1):
# we have been handling a range and this is the
# bookend of the range, but because we look at
# next value we have to alternatively test last
# value in list
print_list.append('-')
print_list.append(p[i])
# return as a compiled string element for pasting into printer dialog
return ''.join(str(x) for x in print_list)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment