Skip to content

Instantly share code, notes, and snippets.

@dgladkov
Created September 6, 2012 21:30
Show Gist options
  • Save dgladkov/3660508 to your computer and use it in GitHub Desktop.
Save dgladkov/3660508 to your computer and use it in GitHub Desktop.
Generates string range, analog of Perl's `print "a".."azc"`
from itertools import product
def string_range(first, last):
"""
Generates string range, analog of Perl's `print "a".."azc"`
Usage: string_range('a', 'azc')
"""
def ascii_generator(letters):
"""
Iterates single letters in provided single or multiple letter range
like ab-zz, where 'ab' is an argument passed to the function.
"""
for l in letters:
i = ord(l)
while i <= ord('z'):
yield chr(i)
i = i + 1
min_length = len(first) - 1
for k in range(len(last)):
if k < min_length:
continue
for x in product(ascii_generator(first), repeat=k + 1):
result = ''.join(x)
yield result
if result == last:
return
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment