Generate a string of random numbers with a specific length

1

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

    
asked by oskr 31.05.2018 в 12:33
source

2 answers

1

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 !!

    
answered by 31.05.2018 в 12:49
1

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.
  • We define 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
  • We use an understanding of lists to generate first a list of chains of size size : [str(random.choice(valores)) for _ in range(size)]
  • We use the join() method that each string has, to concatenate a list
answered by 31.05.2018 в 18:01