views:

866

answers:

3

Hello, I want to generate string with N size.

It should be made up of numbers and upper case english letters such as:

  • 6U1S75
  • 4Z4UKK
  • U911K4

How can I achieve this in a pythonic way ?

Thanks

+11  A: 
''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(N))
Ignacio Vazquez-Abrams
exactly how i would have done it :)
Matt Joiner
seems like the best way, always Ignacio as the champion :)
Hellnar
I don't know a lick of python, but holy cow, does this make me want to learn it.
abeger
A: 

Taking the answer from Ignacio, this works with python 2.6:

import random
import string

N=6
print ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(N))

Example output: JQUBT2

quamrana
A: 
  1. Better way is to use random.sample(if you are ok with no repetition, which could be good)
  2. Do not add lists in every iteration

e.g.

import random
import string

char_set = string.ascii_uppercase + string.digits
print ''.join(random.sample(char_set,6))
Anurag Uniyal
This way isn't bad but it's not quite as random as selecting each character separately, as with `sample` you'll never get the same character listed twice. Also of course it'll fail for `N` higher than `36`.
bobince
for the given use case(if no repeat is ok) i will say it is still the best solution.
Anurag Uniyal
One of the examples has a repeat, so I doubt he is looking to disallow repeats.
Mark Byers