Francesc Francesc - 6 months ago 13
Python Question

How do I generate a ranndom number or letter with certain rules in python

I'm trying to generate a random number but with certain rules.
The first 11 digits to be

00000001008
so I just made it a string and printed it to the screen then after the string, the next number is a random digit or a letter, so I'm using the random and string module to generate a random digit or letter. After the random generated number I want a set of three 1's so I just printed them as a string like I did with the first eleven values. But here's where I'm getting stuck, after the set of three 1's I want to generate another random number or letter and I can't figure it out, I tried the same line of code as the random variable, with a new variable name and then I tried to concatenate it with the new variable in the print statement and it gives me an error. How can I generate another random number after the three 1's?

import random
import string

random = ''.join([random.choice(string.ascii_letters + string.digits) for n in xrange(1)])

print ("00000001008")+ random + ("111")


Output



00000001008U111


Desired Output



00000001008(random)111(random)1(random)


Error



import random
import string

random = ''.join([random.choice(string.ascii_letters + string.digits) for n in xrange(1)])
random1 = ''.join([random.choice(string.ascii_letters + string.digits) for n in xrange(1)])
print ("00000001008")+ random + ("111") + random1


random1 = ''.join([random.choice(string.ascii_letters + string.digits) for n in xrange(1)])
AttributeError: 'str' object has no attribute 'choice'

Answer

you can simply use string formatting and 3 random values

import random
import string

def gen():
  return random.choice(string.ascii_letters + string.digits)

print('00000001008%s111%s1%s' % (gen(), gen(), gen()))

and the only problem why your code is not working is that you named your variable random, which made module random impossible to access, thus error coming from your random.choice call which now refers to a string. Rename your variables to "random_string" and "random_string1" and everything will be just fine.