I wanted to know how I could create a string of random numbers by entering the length that the string should have. For example, that the program generates a list between 1 and 9 and has a length of 3 characters. Thanks
I wanted to know how I could create a string of random numbers by entering the length that the string should have. For example, that the program generates a list between 1 and 9 and has a length of 3 characters. Thanks
If I understood you correctly, it would be something like this:
import random
result = []
for x in range(0,3):
result.append(random.randint(0,9))
print result
The result is the following (it could have been other numbers):
[0, 5, 8]
Each time you run the script it will give you a different result. Hope it has fit. Greetings !!
A very simple way, is to use random.choice()
that gets a random value from a certain list:
import random
valores = [2,4]
size = 3
random.seed(5) # Esto solo para hacer reproducible el ejemplo
print("".join([str(random.choice(valores)) for i in range(size)]))
442
Details:
random.seed(5)
you can delete it, it's just to set the initial seed, and make the example reproducible, so if you run the code the result will be the same as I get. valores
with the list of values from which we want to obtain each part of the chain and the size of the same in size
size
: [str(random.choice(valores)) for _ in range(size)]
join()
method that each string has, to concatenate a list