Python - Join list with new line
Python - Join list with new line character
To join a given list of elements into a Python string, with a new line character as separator between the elements, call string join() method on new line "\n", and pass the given list as argument to the method. The method returns a new string created by joining the elements in the list with the new line character in between them.
In this tutorial, we shall go through some examples where we join the elements in a Python list with new line character.
1. Join elements of a Python list with new line as separator using string join()
Consider that we are given a list of string elements, and we have to join them into a string with new line character as separator.
Steps
- Given a list in my_list.
- Call string join() method on new line character (taken as string literal), and pass the list as argument.
'\n'.join(my_list)
- The join() method returns a string created by joining the elements in the list with the new line character in between them. Assign the returned value to a variable, say joined_str.
- You may print the returned string to standard output using print() statement.
Program
The complete program to join the elements of a list with new line character as separator.
Python Program
# Given a list
my_list = ['apple', 'banana', 'cherry']
# Join elements in list with new line
joined_str = '\n'.join(my_list)
print(joined_str)
Output
apple
banana
cherry
Summary
In this tutorial, we have seen how to join a list of elements with new line using string join() method, with examples.