Search code examples
pythonlistsplitnewlinestrip

How to remove newline from end and beginning of every list element [python]


I've got the following code:

from itemspecs import itemspecs
x = itemspecs.split('#@#')
res = []
for item in x:
    res.append(item.split('##'))
print(res)

This imports a string from another document. And gives me the following:

[['\n1\nWie was de Nederlandse scheepvaarder die de Spaanse zilvervloot veroverde?\n',
  '\nA. Michiel de Ruyter\nB. Piet Heijn\nC. De zilvervloot is nooit door de Nederlanders
 onderschept\n', '\nB\n', '\nAntwoord B De Nederlandse vlootvoogd werd hierdoor bekend.\n'], 
['\n2\nIn welk land ligt Upernavik?\n', '\nA. Antartica\nB. Canada\nC. Rusland\nD. 
Groenland\nE. Amerika\n', '\nD\n', '\nAntwoord D Het is een dorp in Groenland met 1224 
inwoners.\n']]

But now I want to remove all the \n from every end and beginning of every element in this list. How can I do this?


Solution

  • You can do that by stripping "\n" as follow

    a = "\nhello\n"
    stripped_a = a.strip("\n")
    

    so, what you need to do is iterate through the list and then apply the strip on the string as shown below

    res_1=[]
    for i in res:
        tmp=[]
        for j in i:
            tmp.append(j.strip("\n"))
        res_1.append(tmp)
    

    The above answer just removes \n from start and end. if you want to remove all the new lines in a string, just use .replace('\n"," ") as shown below

    res_1=[]
    for i in res:
        tmp=[]
        for j in i:
            tmp.append(j.replace("\n"))
        res_1.append(tmp)