Print random numbers on same line inside f string

Question:

I’m trying to generate random numbers onto the same line and I am having some issues with the formatting.

I am trying to shorten my long code below into something more efficient code wise:

import random

randomnumber1 = random.randint(1,99)
randomnumber2 = random.randint(1,99)
randomnumber3 = random.randint(1,99)
randomnumber4 = random.randint(1,99)
randomnumber5 = random.randint(1,99)
randomnumber6 = random.randint(1,99)
lucky_numbers = f"{randomnumber1}-{randomnumber2}-{randomnumber3}-{randomnumber4}-{randomnumber5}-[{randomnumber6}]"
print(lucky_numbers)

Output is this:

31-29-31-50-69-[14]

After a few attempts, my new code is this:

for i in range(5):
    first_half=print(f"{random.randint(1,99)}-", end="")
print(f"{first_half}-[{random.randint(1,99)}]")

However, whenever I run it the output is this:

77-41-39-32-74-None-[29]

How do I stop the ‘None‘ from appearing in my output and also why is it appearing? Thanks

Asked By: gfran

||

Answers:

You assign print to first_half and print return None. You can use '-'.join.

first_half = '-'.join(str(random.randint(1,99)) for _ in range(5))
print(f"{first_half}-[{random.randint(1,99)}]")

63-55-77-71-81-[47]

Explanation:

# list comprehension
>>> [str(random.randint(1,99)) for _ in range(5)]
['94', '7', '15', '86', '54']

# use '-'.join()
>>> '-'.join(str(random.randint(1,99)) for _ in range(5))
'94-7-15-86-54'
Answered By: I'mahdi

a bit shorter:

from random import choices

>>> '{}-{}-{}-{}-{}-[{}]'.format(*choices(range(1,100), k=6))

'79-48-93-81-18-[72]'
Answered By: SergFSM
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.