Reputation: 63
I'm generating a list of random digits, but I'm struggling to figure out how to output the digits in a single row without the square brackets?
import random
def generateAnswer(answerList):
listofDigits = []
while len(listofDigits) < 5:
digit = random.randint(1, 9)
if digit not in listofDigits:
listofDigits.append(digit)
return listofDigits
def main():
listofDigits = []
print(generateAnswer(listofDigits))
main()
Upvotes: 0
Views: 746
Reputation: 872
Try this:
listofDigits = []
print(str(generateAnswer(listofDigits))[1:-1])
Also, if generateAnswer
initialize and return the list, then you don't need to pass in an empty list. Another thing is that if you want to generate a non-repeating random list, you can use random.sample
and range
.
I think this is better:
import random
def generateAnswer():
return random.sample(range(1, 10), 5)
def main():
print(str(generateAnswer())[1:-1])
main()
Hope it helps!
Upvotes: 3
Reputation: 164823
You can unpack a list and use the sep
argument:
print(*generateAnswer(listofDigits), sep=' ')
Upvotes: 4
Reputation: 5680
The reason you’re getting the brackets is because the list
class, by default, prints the brackets. To remove the brackets, either use a loop or string.join:
>>> print(' '.join(map(str, listofDigits)))
9 2 1 8 6
>>> for i in listofDigits:
print(i, end=' ')
9 2 1 8 6
Note that the last method adds a space at the end.
Note that in the first method, the arguments need to be cast to strings because you can only join
strings, not ints.
Upvotes: 1