在stackoverflow上看到这样的问题:
需要用python生成由数字和大写字母组成的随机字符串,如:
这个需求可以用一行python语句解决:
''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N))
当然,上面的语句存在一个问题。This is an excellent method, but the PRNG in random is not cryptographically secure. I assume many people researching this question will want to generate random strings for encryption or passwords. You can do this securely by making a small change in the above code:
''.join(random.SystemRandom().choice(string.uppercase + string.digits) for _ in xrange(n))
Using random.SystemRandom() instead of just random uses /dev/urandom on *nix machines and CryptGenRandom() in Windows. These are cryptographically secure PRNGs. Using random.choice instead of random.SystemRandom().choice in an application that requires a secure PRNG could be potentially devastating, and given the popularity of this question, I bet that mistake has been made many times already.