How to remove “\n” in a list of lists (python)

北慕城南 提交于 2019-12-11 13:20:08

问题


I have a giant list of lists that I imported from a file like this:

letters = []
for i in range(len(string)):
    let = []
    for j in range(7):
        line = infile.readline()
        let = let + [line]
    letters.append(let)
    infile.readline()

Its a big list of lists, but each secondary list has a \n at the end of it.

[['   ###   \n', '  ## ##  \n', ' ##   ## \n', '##     ##\n', 
'#########\n', '##     ##\n', '##     ##\n'], ['######## \n',
'##     ##\n', '##     ##\n', '######## \n', '##     ##\n',
'##     ##\n', '######## \n'], ... ]]

How do I remove the \n? so its just

[['   ###   ', '  ## ##  ', ' ##   ## ', '##     ##', 
'#########', '##     ##', '##     ##'], ['######## ',
'##     ##', '##     ##', '######## ', '##     ##',
'##     ##', '######## '], ... ]]

It's important to have the spaces in there as well. I've tried doing

 letters.strip("\n")

but that didnt work.

Please help!

EDIT: I think it might be a problem with the

line = infile.readline()

but I'm not sure how to fix it.

My desired output is

    ###    #######  ########

but instead i'm getting this

    ###
  #######
 ########

回答1:


Wherever your current code has a call to .readline(), make it .readline().rstrip('\n') instead.




回答2:


Try:

line = infile.readline()
line = line.strip('\n')
let = let + [line]



回答3:


If you want to remove \n from the last element only, use this:

t[-1] = t[-1].strip()

If you want to remove \n from all the elements, use this:

t = map(lambda s: s.strip(), t)

You might also consider removing \n before splitting the line:

line = line.strip()


来源:https://stackoverflow.com/questions/36990675/how-to-remove-n-in-a-list-of-lists-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!