Reputation: 321
I'm reading from a file and storing each character in a two dimensional array. I'm trying to get rid of the '\n' that comes at the end of each line. My code so far is:
l = []
for i in range(5):
l.append([])
f = open('file.txt','r')
count = 0
for line in f:
for char in line:
l[count].append(char)
count += 1
f.close()
l[0].rstrip('\n')
I have tried instead of the l[0].rstrip('\n')
:
l = map(lambda s: s.strip('\n'), l)
and
l = [i.rstrip() for i in l ]
Each of these return the error that list has no attribute strip (or rstrip). Is there anyway to fix this?
Upvotes: 1
Views: 3057
Reputation: 477309
l
is a list of lists. So if you call l[0].rstrip()
you can rstrip()
on the sublist. But even if strip()
would have worked, you would not have seen any difference since strings are immutable, and thus it will return a new string, not update the older one.
You can however easily use:
l[0] = [x.rstrip('\n') for x in l[0]]
to update only l[0]
.
If you want to update all the sublists, you can use the following list comprehension:
l = [[x.rstrip('\n') for x in s] for s in l]
Furthermore the code for reading your file into memory is quite weird: it will only work if the file has less than six lines. You can use the following approach:
with open('file.txt','r') as f:
l = [list(line.rstrip('\n')) for line in f]
this replaces the entire code fragment in the question.
Upvotes: 2