How to remove \n from list elements in Python – last character new line

Hello Python learners, in this Python tutorial, you will learn how to remove the last character \n from list elements in Python. In some situation, you will face the problem that, in your list, for every items, there is a \n as the last character. You may get confused if it is an empty character or a \n.

Today I am here to help you out to get rid of this \n from list elements in Python.

In my last tutorial, I have shown you how to add items to a list from a text file line by line in Python.

my_file = open('my_text_file.txt')
all_the_lines = my_file.readlines()
items = []
for i in all_the_lines:
    items.append(i)
print(items)

And we got an output like this below:

$ python codespeedy.py
['This\n', 'is\n', 'a text\n', 'file\n', 'And we\n', 'are going to\n', 'add\n', 'these\n', 'lines\n', 'to a list\n', 'in Python']

So you can see there are \n to each and every list elements in my list.

In this tutorial, I will show you how to omit that \n.

Python program to remove \n from list elements

Just create a new list and use the below code.

new_items = [x[:-1] for x in items]
print(new_items)

Output:

['This', 'is', 'a text', 'file', 'And we', 'are going to', 'add', 'these', 'lines', 'to a list', 'in Pytho']

Now you can see there is no \n there.

You can also read some other tutorials related to text files:

Leave a Reply

Your email address will not be published. Required fields are marked *