2015-04-01 78 views
0

如何刪除字符串中的其他內容並返回由其他字符串組成的列表?這是我寫的。提前致謝!!!刪除字符串中的項目

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 
+0

這非常含糊,除非您發佈了帶有代碼的示例輸入。編寫文本描述並不能解決問題的模糊性 – ha9u63ar 2015-04-01 22:51:46

回答

1

splitstrip可能是你需要的東西:

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.'] 

不知道其中+適合的,因爲它是,如果它是某種要麼條參與或者str.replace它,也避免使用list作爲變量名,它會影響Python的list

最後字符串沒有remove方法,你可以.replace但由於字符串是不可變的需要的poem重新分配的返回值取代IE poem = poem.replace("+","")

0

你可以閱讀所有非空行像這樣:

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

不看你的輸入樣本,我假設你只是想要你的空白處被刪除。在這種情況下,

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

'如果line.strip'將檢查空行並使用枚舉(如果您需要迭代元素的索引)。另外''\ s「'是什麼?你認爲替換是重新嗎? – 2015-04-01 23:03:00

+0

@PadraicCunningham當你評論時,我正在編輯片段....現在應該是不同的 – ha9u63ar 2015-04-01 23:07:09

+0

如果'.replace(「」,「」)'將替換所有空間,即'foo bar foobar - > foobarfoobar' – 2015-04-01 23:09:32