0

I want to create a random list of names from a from a bigger list of names. The problem is, there is no space between the names that are generated. I cannot understand how to put space. Here's my code

import random

final_list = ""

a=0

sss = ("John","Adam","Sara","Lory","Dick","Popeye")

while a<7:

    x = random.choice(sss)

    final_list += x

    a += 1

print (final_list) 

The result is something like this: SaraAdamDickPopeyeSaraPopeyeLory

How can I add space between the names? Also, can anyone suggest a shorter way to do this code?

wwii
  • 23,232
  • 7
  • 37
  • 77
Hamza Khalid
  • 221
  • 3
  • 12
  • Welcome to SO. Please take the time to read [ask]. [Which is the preferred way to concatenate a string in Python?](https://stackoverflow.com/questions/12169839/which-is-the-preferred-way-to-concatenate-a-string-in-python) may be helpful. Please fix the indentation. – wwii Oct 21 '17 at 15:28

2 Answers2

0

You can add an additional empty empty string at the original concatenation:

x = random.choice(sss)
final_list += " "+x if final_list else x
a += 1

Or, more precisely, use ' '.join in list comprehension:

sss = ("John","Adam","Sara","Lory","Dick","Popeye")
final_string = ' '.join(random.choice(sss) for i in range(7))
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
0

To avoid leading or trailing spaces, check if length of final_list is already greater than zero.

import random

final_list = ""
a=0
sss = ("John","Adam","Sara","Lory","Dick","Popeye")
while a<7:
    x = random.choice(sss)
    final_list = final_list + " " + x if len(final_list) > 0 else x
    a += 1
print (final_list) 

If you don't want explicit checking, you can make use of strip function to remove leading and trailing spaces after you construct the final_list.

Prasad
  • 5,946
  • 3
  • 30
  • 36