-2

I change the list into a string but it is not printing on the same line

spam= ['apples', 'bananas', 'tofu', 'cats']
for i in spam:
    print(str(i))
  • 2
    This isn't really turning it into a string, but `print`ing the individual elements. That being said, `print(i, end=' ')` seems to be what you're after. Or simply, `print(' '.join(spam))`. – Axe319 Dec 31 '22 at 21:06
  • Does this answer your question? [How to concatenate (join) items in a list to a single string](https://stackoverflow.com/questions/12453580/how-to-concatenate-join-items-in-a-list-to-a-single-string) – SpeedoThreeSixty Dec 31 '22 at 21:08
  • `str(spam)` perhaps? – Diego Torres Milano Dec 31 '22 at 21:08
  • 2
    Welcome to Stack Overflow! Please take the [tour] and read [ask]. – wjandrea Dec 31 '22 at 21:13

1 Answers1

0

Since you are printing each item in the list individually using the for loop, they wont print in the same line. To print them on the same line do the following instead of using a loop:

spam= ['apples', 'bananas', 'tofu', 'cats']

print (', '.join(spam))

Output:

apples, bananas, tofu, cats

You can optionally set a single space to show them separately like the following.

print(' '.join(spam))

Output:

apples bananas tofu cats
wjandrea
  • 28,235
  • 9
  • 60
  • 81