I've been trying to find a more pythonic way of generating random string in python that can scale as well. Typically, I see something similar to
''.join(random.choice(string.letters) for i in xrange(len))
It sucks if you want to generate long string.
I've been thinking about random.getrandombits for a while, and figuring out how to convert that to an array of bits, then hex encode that. Using python 2.6 I came across the bitarray object, which isn't documented. Somehow I got it to work, and it seems really fast.
It generates a 50mil random string on my notebook in just about 3 seconds.
def rand1(leng): nbits = leng * 6 + 1 bits = random.getrandbits(nbits) uc = u"%0x" % bits newlen = int(len(uc) / 2) * 2 # we have to make the string an even length ba = bytearray.fromhex(uc[:newlen]) return base64.urlsafe_b64encode(str(ba))[:leng]
edit
heikogerlach pointed out that it was an odd number of characters causing the issue. New code added to make sure it always sent fromhex an even number of hex digits.
Still curious if there's a better way of doing this that's just as fast.
The random module in python is used to generate random strings. The random string is consisting of numbers, characters and punctuation series that can contain any pattern. The random module contains two methods random. choice() and secrets. choice(), to generate a secure string.
In Python, you can randomly sample elements from a list with choice() , sample() , and choices() of the random module. These functions can also be applied to a string and tuple. choice() returns one random element, and sample() and choices() return a list of multiple random elements.
Example 1: Generate Random Strings In the above example, the Math. random() method is used to generate random characters from the specified characters (A-Z, a-z, 0-9). The for loop is used to loop through the number passed into the generateString() function. During each iteration, a random character is generated.
import os random_string = os.urandom(string_length)
and if you need url safe string :
import os random_string = os.urandom(string_length).hex()
(note random_string length is greatest than string_length in that case)
Sometimes a uuid is short enough and if you don't like the dashes you can always.replace('-', '') them
from uuid import uuid4 random_string = str(uuid4())
If you want it a specific length without dashes
random_string_length = 16 str(uuid4()).replace('-', '')[:random_string_length]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With