Search code examples
pythonprintingtrailing

What Is The Python 3 Equivalent to This


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?


Solution

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

    print(' '.join(my_list))
    

    or

    print(*my_list)