Generate all strings up to desired length
Question: I want to generate all the random strings having length varying from 1 till
max_length. Is is there an in-built function in python that would do that? If
not, please tell me how to do this or direct me to posts which covers this
type of problem. Thanks in advance.


Answer: Random strings:

    
    
    import random
    def get_random_string(alphabet, slen):
        return ''.join(random.choice(alphabet) for _ in xrange(slen))
    
    print get_random_string('0123456789', 5) # prints e.g. 62247
    

All strings in lexicographical order (thanks @DSM for reminding me about
`itertools`):

    
    
    import itertools
    def gen_all_strings(alphabet, slen):
        it = itertools.product(alphabet, repeat=slen)
        return (''.join(s) for s in it)
    
    print list(gen_all_strings('abc', 2)) # prints ['aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc']
    

