What is the most lightweight way to create a random string of 30 characters like the following?
ufhy3skj5nca0d2dfh9hwd2tbk9sw1
And an hexadecimal number of 30 digits like the followin?
8c6f78ac23b4a7b8c0182d7a89e9b1
To generate a random hex string in Python, use one of the two functions from the secrets module – token_hex(n) or choice() – if security is a concern. What is this? Otherwise, you can use the choice() function from the random module.
Using the random index number, we have generated the random character from the string alphabet. We then used the StringBuilder class to append all the characters together. If we want to change the random string into lower case, we can use the toLowerCase() method of the String .
To generate Random Hexadecimal Bytes, first, a random byte can be generated in decimal form using Java. util. Random. nextInt() and then it can be converted to hexadecimal form using Integer.
I got a faster one for the hex output. Using the same t1 and t2 as above:
>>> t1 = timeit.Timer("''.join(random.choice('0123456789abcdef') for n in xrange(30))", "import random") >>> t2 = timeit.Timer("binascii.b2a_hex(os.urandom(15))", "import os, binascii") >>> t3 = timeit.Timer("'%030x' % random.randrange(16**30)", "import random") >>> for t in t1, t2, t3: ... t.timeit() ... 28.165037870407104 9.0292739868164062 5.2836320400238037
t3
only makes one call to the random module, doesn't have to build or read a list, and then does the rest with string formatting.
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