1

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

    ###
  #######
 ########
Jackson Hopey
  • 11
  • 1
  • 3

3 Answers3

3

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

jez
  • 14,867
  • 5
  • 37
  • 64
1

Try:

line = infile.readline()
line = line.strip('\n')
let = let + [line]
gsamaras
  • 71,951
  • 46
  • 188
  • 305
  • Strings don't get modified in-place in standard Python. Your output of .strip() is not being used. – jez May 02 '16 at 20:14
  • 1
    Yes, said jez, and then padded his comment to reach the minimum length. – jez May 02 '16 at 20:33
0

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()
Ahmed farag mostafa
  • 2,802
  • 2
  • 14
  • 33
  • Why not use [**`string.strip`**](https://docs.python.org/2/library/string.html#string.strip) instead of defining the `lambda`? – Peter Wood May 02 '16 at 20:07