Print multiple variables on separate lines in Python

avatar

Borislav Hadzhiev

Last updated: Sep 5, 2022

banner

Photo from Unsplash

Print multiple variables on separate lines in Python #

Use the sep argument of the print() function to print multiple variables on separate lines, e.g. print(var1, var2, var3, sep='\n'). When the sep argument is set to a newline character, the print() function prints the supplied values on separate lines.

main.py
# ✅ print multiple variables on separate lines (sep) var1 = 'bobby' var2 = 'hadz' var3 = 'com' # bobby # hadz # com print(var1, var2, var3, sep='\n') # ------------------------------------------- # ✅ print multiple variables on separate lines (str.join()) result = '\n'.join([var1, var2, var3]) # bobby # hadz # com print(result)

The first example uses the sep argument of the print() function to print multiple variables on separate lines.

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'

We set the sep argument to a newline (\n) character to print the variables on separate lines.

main.py
var1 = 'bobby' var2 = 'hadz' var3 = 'com' # bobby # hadz # com print(var1, var2, var3, sep='\n')

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

Print multiple variables on separate lines using str.join() #

To print multiple variables on separate lines:

  1. Use the str.join() method to join the iterable's elements into a string with a newline (\n) separator.
  2. Use the print() function to print the string.
main.py
# 👇️ for strings var1 = 'bobby' var2 = 'hadz' var3 = 'com' result = '\n'.join([var1, var2, var3]) # bobby # hadz # com print(result)

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 = 10 var2 = 50 var3 = 100 result = '\n'.join(str(num) for num in [var1, var2, var3]) # 10 # 50 # 100 print(result)

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

We used a generator expression to iterate over the list in the example.

Generator expressions are used to perform some operation for every element or select a subset of elements that meet a condition.

On each iteration, we convert the current number to a string and return the result.

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.