Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most lightweight way to create a random string and a random hexadecimal number

Tags:

python

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

like image 871
xRobot Avatar asked May 06 '10 15:05

xRobot


People also ask

How do you generate a random hex string in Python?

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.

How do you generate random strings?

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 .

How do you generate a random hexadecimal in Java?

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.


1 Answers

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.

like image 136
jcdyer Avatar answered Oct 03 '22 10:10

jcdyer