TransWikia.com

Not able to delete n

Stack Overflow Asked by user13645394 on August 26, 2020

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\nn']]

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 155402n 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!

3 Answers

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])

Correct answer by Tom on August 26, 2020

In the last item in the list, there is actually only one newline character, not two. The backslash "escapes" the newline character so there is only 1. It is not deleting the second newline character because there isn't a second newline character. Change ' 155402\nn' to ' 155402nn' if you want 2 newlines.

Answered by aidan0626 on August 26, 2020

The extra is affecting the split. So what you need to do is replace the extra "" with ""

Try:

lists[-1].replace("\\", "\").split("n")

Answered by ewong on August 26, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP