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?:


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 ""


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

Answered by ewong on August 26, 2020

Add your own answers!

Related Questions

Unable to understand error in D flip flop code

2  Asked on November 29, 2021 by chaitanya_12789


Git: Stashed Changes But Still Can’t Pull

1  Asked on November 29, 2021 by crawfordbenjamin


elif a==”no”: ^ SyntaxError: invalid syntax

3  Asked on November 29, 2021 by mayar-kurdi


ValueError: Unconverted data remains .000

2  Asked on November 29, 2021 by vbdashes


How to make an arraylist for the last dice rolls?

3  Asked on November 29, 2021 by acidixs


XMLRead all same Notes

2  Asked on November 29, 2021 by ddave


Find the most frequent words that appear in the dataset

3  Asked on November 29, 2021 by pythonnew


Jenkins auto generates wrong config for composer

1  Asked on November 29, 2021 by tiny-sunlight


Ask a Question

Get help from others!

© 2022 All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP, SolveDir