Maybe a very simple answer but I cannot seem to get rid of a newline character. I have a list that contains a list and it looks like this:
[['US', ' 146465', ' 146935', ' 148012', ' 149374', ' 150822', ' 152055', ' 153315', ' 154448', ' 154862', ' 155402\\n\n']]
At the end there are two newline characters and I need to get rid of them. So first I iterated thought the big list to arrive at the sublist.
for lists in L:
Now that I am there I want to get the last element of the list using list[-1]
When I print this I get 155402\n
Where did the second newline go? So I continue, now I guess the only thing to do is split it at the newline right?:
print(lists[-1].split('\n'))
My output:
[' 155402\\n', '']
What in the world! Now there is a a double slash before the newline. So turns out I am incapable of taking out a simple newline character:D So really my question is how can I get rid of a newline in lists of a list. Any help would be appreciated. Thank you!
Another slightly different regex approach - you can catch both new line characters OR double backslashed n
:
import re
for lists in L:
lists[-1] = re.sub('\\\\n|\n', '', lists[-1])
Or out of a loop
L[0][-1] = re.sub('\\\\n|\n', '', L[0][-1])