1

What is the Python 3 equivalent to Python 2's statement:

print x,

I am aware of Python's 3

print(x,end=' ')

However this is not exactly the same as I will demonstrate.

So lets say I had a list of items I wanted to print out all on one line with spaces in between each item BUT NOT after the last item.

In Python 2 it is just simply:

for x in my_list:
    print x,

However if we use the Python 3 approach above it will produce the list of items on one line but will have trailing white space after the last item.

Does Python 3 have a nice elegant solution to produce the same results as in the Python 2 statement?

Blued00d
  • 170
  • 4
  • 23

2 Answers2

1

Unless you need to print each element on their own, you can do:

print(' '.join(my_list))

or

print(*my_list)
Tordek
  • 10,628
  • 3
  • 36
  • 67
0

If you do not require the loop, you can just print it all at once:

print(" ".join(my_list))
Tordek
  • 10,628
  • 3
  • 36
  • 67
Carsten
  • 17,991
  • 4
  • 48
  • 53