Print values separated by spaces instead of new lines in Python

avatar

Borislav Hadzhiev

Last updated: Sep 6, 2022

banner

Photo from Unsplash

Print values separated by spaces instead of new lines in Python #

Use the end argument of the print() function to print values separated by spaces instead of new lines, e.g. print(item, end=' '). When the end argument is set a space, a space is printed at the end of each message instead of a newline character.

main.py
var1 = 'bobby' var2 = 'hadz' for item in [var1, var2]: print(item, end=' ') # 👉️ bobby hadz # ------------------------------------------- # 👇️ using str.join() result = ' '.join([var1, var2]) print(result) # 👉️ bobby hadz
We used the end argument of the print() function to separate values by spaces instead of newline (\n) characters when printing.

The end argument is printed at the end of the message.

By default, end is set to a newline character (\n).

main.py
for item in ['bobby', 'hadz']: # bobby # hadz print(item) for item in ['bobby', 'hadz']: # bobby hadz print(item, end=' ')

The print() function also takes a sep argument.

The sep argument is the separator between the arguments we pass to print().

By default, the argument is set to a space.

main.py
print('a', 'b', 'c') # 👉️ 'a b c' print('a', 'b', 'c', sep='') # 👉️ 'abc'

Alternatively, you can use the str.join() method.

To print values separated by spaces instead of new lines:

  1. Use the str.join() method to join the values with a space separator.
  2. Use the print() function to print the result.
main.py
var1 = 'bobby' var2 = 'hadz' result = ' '.join([var1, var2]) print(result) # 👉️ bobby hadz

The str.join method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.

Note that the method raises a TypeError if there are any non-string values in the iterable.

If your iterable contains numbers or other types, convert all of the values to strings before calling join().

main.py
var1 = 4 var2 = 8 result = ' '.join(str(num) for num in [var1, var2]) print(result) # 👉️ 4 8

The string the method is called on is used as the separator between the elements.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.