Home > Software design >  generate random numbers in python with quotes
generate random numbers in python with quotes

Time:07-28

Requirement: ["123456","578758",......"837872"] a list of random 6 digit numbers with quotes

What I have tried:

res = random.sample(range(10000, 999999), 45)
for i in range(5000):  
  print ('{"products":' '"' str(res) '"' '}')
  print("\n")

I am new to python so please do suggest on how can I achieve the requirement

CodePudding user response:

[str(x) for x in random.sample(range(10000, 999999), 45)]

CodePudding user response:

There are a lot of issues with your syntax.

  1. You're taking 45 random samples despite only needing 6
  2. You wrote a loop that performs 5000 iterations
  3. Your print statement is strange

Issue 1

The second argument passed to random.sample specifies the number of samples you want. If you truly want 6 random samples the syntax should be: random.sample(range(10000, 9999999), 6)

Issue 2

When you say for i in something, you are instructing your loop to iterate through each item in something. In your case it is the numbers 0-4999. This is besides the point because you don't need a loop to accomplish your objective.

Issue 3

As stated above, you don't need to use a for loop for this. But if you really wanted to, construct it like this:

for i in res: 
    print(str(res))

A better way to do this:

I'm going to go out on a limb and assume you want these values stored in an array due to your description of your requirement.

If that's the case I recommend using map.

This would look like:

list(map(str, random.sample(range(10000, 9999999), 6)))

If you want to print them:

print(*list(map(str, random.sample(range(10000, 9999999), 6))), sep='\n')

Outputs

list(map(str, random.sample(range(10000, 9999999), 6)))
OUTPUT>>> ['1696162', '394420', '9290621', '624215', '3367247', '2571869']

print(*list(map(str, random.sample(range(10000, 9999999), 6))), sep='\n')
OUTPUT>>> 
5957168
446219
611119
6518976
4197232
3394411

Notes

Quotations won't show in the console when you print strings. Don't worry though. Because we mapped the 6 values to strings, the quotes are there for all intents and purposes.

The asterisk that starts off the print statement tells Python to consider all values.

You also don't have to write a second print statement to create a new line after each value. This can be done by passing the sep argument to print and assigning it the value of '\n' like: print(*something, sep='\n'). This will print each new value on a new line.

  • Related