Skip to main content

How to Join Strings and Lists with Newlines in Python

Inserting newline characters (\n) when joining strings or list elements is a common formatting task in Python.

This guide demonstrates how to use the newline character with string concatenation, f-strings, and the str.join() method to create multi-line output from your data.

Joining a List with Newline Characters

The most efficient way to join a list of strings with newline characters is using the str.join() method:

my_list = ['tutorial', 'reference', 'com']
result = '\n'.join(my_list)

print(result)

Output:

tutorial
reference
com
  • The '\n'.join(my_list) concatenates all strings from the list into a single string, inserting a newline character (\n) between each element.

Handling Non-String List Elements

The str.join() method expects an iterable of strings. If your list contains other data types (numbers, booleans, etc.), you need to convert them to strings first. Use the map() function for this:

my_list = ['tutorial', 'reference', 'com', 4, 5]
result = '\n'.join(map(str, my_list)) # Convert to string before joining

print(result)

Output:

tutorial
reference
com
4
5
  • The map(str, my_list) calls the str() function for every item in the list, creating an iterator that will return the string representation of all items.

Joining Two Strings with a Newline

To combine two (or more) individual strings with a newline separator, you have several options.

Using the Addition Operator (+)

The simplest way is to use the addition operator to concatenate the strings with the newline character:

string1 = 'tutorial'
string2 = 'reference'
result = string1 + '\n' + string2
print(result)

Output:

tutorial
reference

Using f-strings

F-strings (formatted string literals) provide a more readable way to embed newlines:

string1 = 'tutorial'
string2 = 'reference'
result = f'{string1}\n{string2}\n.com'
print(result)

Output:

tutorial
reference
.com
  • Using f-strings to construct multi-line strings is much more readable than concatenation, specially when working with multiple values.

Using str.join()

If the strings you want to join are already stored in a list, use join():

a_list = ['tutorial', 'reference', '.com']
result = '\n'.join(a_list)
print(result)

Output:

tutorial
reference
.com