Reputation: 1
I encountered a line of python code like this:
''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(8))
It's kind of confusing.. anyone know what it does?
Upvotes: -1
Views: 50
Reputation: 10379
''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(8))
When you see an expression like this, the best is to take it apart, step by step.
''
is an empty string.join(...)
will join all characters (the ... part) and add it to the empty stringrandom.choice(...)
will choose any character at randomstring.ascii_lower + string_digits
creates a string that contains all lower case characters and all digitsfor _ in range(8)
means this is done 8 times (technically, this is a generator expression)As a result, the whole expression returns a random string of 8 characters, all lower case or digits.
To learn more about generator expressions, Dan Bader has a nice tutorial. If you're wondering how one comes up with an expression like this, the best is to study the Python documentation, the official tutorial is a good start.
Upvotes: 2
Reputation: 438
I tried this piece of code:
import random
import string
a = 'abcdefghijk'
print(a.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(8)))
It gave me this output:
tabcdefghijk2abcdefghijk7abcdefghijktabcdefghijklabcdefghijkoabcdefghijkfabcdefghijk0
I believe it takes an input string and sticks it together 7 times with either a random lowercase letter or a random digit. (7 times because there is one on either end and there are therefore 8 joining digits).
Upvotes: 0