The goal of my codes are to write a function and return a list of strings, in which the successive strings (fruit name) correspond to the consecutive #No.1...#No.5 . The whole name of the fruit was split over multiple lines, and I want to display the fruit name in the list as a single string with no whitespace.
I expect my codes return:
['Pear', 'Apple', 'Cherry', 'Banana', 'Peach']
but I got:
['', 'Pear', 'Apple', 'Cherry', 'Banana', 'Peach']
These are the contents of my file fruit.txt:
#NO.1
P
ear
#NO.2
A
pp
l
e
#NO.3
Cherry
#NO.4
Banan
a
#NO.5
Pea
c
h
These are my codes:
def read(filename):
myfile = open('fruit', 'r')
seq = ''
list1 = []
for line in myfile:
if line[0] != '#':
seq +=line.rstrip('\n')
else:
list1.append(seq)
seq = ''
list1.append(seq)
return list1
how to avoid to append an empty string which is not what I want? I suppose I just need to adjust the position a certain line of codes, any suggestion is appreciated.
withconstruct. For further reading, see this link: effbot.org/zone/python-with-statement.htm