Izzy Izzy - 4 months ago 6x
Python Question

How to generate a random string

I'm trying to do a code where is generates a random string, but I have only just started coding so I don't want anything to the code to be too complicated.

import random, string
randomthing = random.choice(string)

But it keeps saying the length (len) is not defined. What should I do?


string module does not have len you might want to try this.

rand_str = lambda n: ''.join([random.choice(string.lowercase) for i in xrange(n)])
# Now to generate a random string of length 10
s = rand_str(10)  

random.choice returns a single character and 10 such characters are joined using the join function.


lambda n : ... creates a lambda function which takes n as the argument.

''.join(sequence) joins a sequence into a string with empty string ('' ) between them i.e. it simply joins characters into words.
'.'.join(['a','b','c']) will for example, return a.b.c.