Carlos
Carlos

Reputation: 59

remove the item in string

How do I remove the other stuff in the string and return a list that is made of other strings ? This is what I have written. Thanks in advance!!!

    def get_poem_lines(poem):
r""" (str) -> list of str

Return the non-blank, non-empty lines of poem, with whitespace removed 
from the beginning and end of each line.

>>> get_poem_lines('The first line leads off,\n\n\n'
... + 'With a gap before the next.\nThen the poem ends.\n')
['The first line leads off,', 'With a gap before the next.', 'Then the poem ends.']
"""

list=[]
for line in poem:
    if line == '\n' and line == '+':
        poem.remove(line)
s = poem.remove(line)
for a in s:
    list.append(a)
return list

Upvotes: 0

Views: 113

Answers (2)

ha9u63a7
ha9u63a7

Reputation: 6854

You can read all non-empty lines like this:

list_m = [line if line not in ["\n","\r\n"] for line in file];

Without looking at your input sample, I am assuming that you simply want your white spaces to be removed. In that case,

for x in range(0, len(list_m)):
    list_m[x] = list_m[x].replace("[ ](?=\n)", "");

Upvotes: 0

Padraic Cunningham
Padraic Cunningham

Reputation: 180481

split and strip might be what you need:

s = 'The first line leads off,\n\n\n     With a gap before the next.\nThen the poem ends.\n'

print([line.strip() for line in s.split("\n") if line])
['The first line leads off,', 'With a gap before the next.', 'Then the poem ends.']

Not sure where the + fits in as it is, if it is involved somehow either strip or str.replace it, also avoid using list as a variable name, it shadows the python list.

lastly strings have no remove method, you can .replace but since strings are immutable you will need to reassign the poem to the the return value of replace i.e poem = poem.replace("+","")

Upvotes: 1

Related Questions