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:
- How to read a specific line from a text file in Python
- How to count the number of lines in a text file in Python
The articles are really helpful to know about different geners of python.
The code is wrong, the last element changed from ‘in Python’ to ‘in Pytho’ 🙂
You can take a look at the first output where I have printed all the list items. The last element does not have a \n or new line character at the end. So you can do one thing here, simply do the same process I have mentioned and do one little change. Loop through (list size – 1) instead of list size. In this way, you will be able to ignore the last element and you will be getting your desired output. Let us know if you have any further queries.
This wouldn’t be as efficient as using the replace function. This can be done by iterating through the array by index and changing each value to the value with “.replace(“\n”,””) ” attached. If anyone has an easier and more robust method please tag me.