Mattr42
Mattr42

Reputation: 95

Removing the [ ] and commas in brackets in a list

I am trying to remove the commas and box brackets [ ] in the list. The program asks the user to enter in the number of values they want randomized within a range of their choosing then displays the results. Currently the program prints out as:

How many #s do you want? 10
Enter the lowest number to generate 1
Enter the highest number to generate 10
[1, 8, 6, 3, 6, 10, 4, 2, 10, 9]

but I need it to display as:

How many #s do you want? 10
Enter the lowest number to generate 1
Enter the highest number to generate 10
1 8 6 3 6 10 4 2 10 9

Maybe I'm going about it incorrectly? Thoughts?

import random

def main():
  numbers = int(input("How many #s do you want? "))
  numbers_2 = int(input("Enter the lowest number to generate "))
  numbers_3 = int(input("Enter the highest number to generate "))

  pop = make_list(numbers, numbers_2, numbers_3)
  print(pop)
  num_string = ""

  for i in sorted(pop):
    num_string += str(i) + " "
  return num_string

def make_list(numbers, numbers_2, numbers_3):
  num_list = []
  for numbers in range(numbers):
    num_list.append(random.randint(numbers_2, numbers_3))
  return num_list

main()

Upvotes: 0

Views: 694

Answers (2)

Philipp F
Philipp F

Reputation: 427

You can do this with print(*pop).

When given several parameters (e.g., print(1, 2, 3), the print command will print them all out, converted to strings, separated by spaces.

With the *, your array pop is unpacked so that it forms the parameters for the print function.

By setting the sep parameter, you can even change the separator. For example, print(*pop, sep=",") would give 1,8,6,3,6,10,4,2,10,9.

Upvotes: 2

iacob
iacob

Reputation: 24181

You are returning the list, and so it is formatted appropriately in the output. To control the formatting, use print e.g.

print(' '.join(map(str,pop)))

Upvotes: 1

Related Questions