Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to generate random strings of a specific length in Python?

Tags:

python

random

For a project, I need a method of creating thousands of random strings while keeping collisions low. I'm looking for them to be only 12 characters long and uppercase only. Any suggestions?

like image 398
Brandon Avatar asked Aug 19 '13 16:08

Brandon


People also ask

How do you generate unique random strings?

There are many ways to generate a random, unique, alphanumeric string in PHP which are given below: Using str_shuffle() Function: The str_shuffle() function is an inbuilt function in PHP and is used to randomly shuffle all the characters of a string passed to the function as a parameter.


1 Answers

CODE:

from random import choice from string import ascii_uppercase  print(''.join(choice(ascii_uppercase) for i in range(12))) 

OUTPUT:

5 examples:

QPUPZVVHUNSN EFJACZEBYQEB QBQJJEEOYTZY EOJUSUEAJEEK QWRWLIWDTDBD 

EDIT:

If you need only digits, use the digits constant instead of the ascii_uppercase one from the string module.

3 examples:

229945986931 867348810313 618228923380 
like image 62
Peter Varo Avatar answered Oct 04 '22 20:10

Peter Varo