2016-09-28 165 views
0

我無法刪除我的列表中的空白。如何刪除列表中的空白

invoer = "5-9-7-1-7-8-3-2-4-8-7-9" 
cijferlijst = [] 

for cijfer in invoer: 
    cijferlijst.append(cijfer.strip('-')) 

我試過以下,但它不起作用。我已經從我的字符串中列出了一個列表,並將所有內容分開,但"-"現在是""

filter(lambda x: x.strip(), cijferlijst) 
filter(str.strip, cijferlijst) 
filter(None, cijferlijst) 
abc = [x.replace(' ', '') for x in cijferlijst] 
+0

'cijferlijst = filter(lambda x:x.strip(),cijferlijst)' – ewcz

+0

爲什麼你只是不用'-'來分割文本? – Kasramvd

+2

爲什麼不這樣'cijferlijst = invoer.split(「 - 」)'?我誤解你正在嘗試做什麼? –

回答

4

試一下:

>>> ''.join(invoer.split('-')) 
'597178324879' 
+0

爲什麼不'替換'? – Kasramvd

+0

@ Kasramvd謝謝!!,但已用於另一個答案... – coder

2

如果你想在字符串中的數字不-,使用.replace()爲:

>>> string_list = "5-9-7-1-7-8-3-2-4-8-7-9" 
>>> string_list.replace('-', '') 
'597178324879' 

如果你想要的數字爲數字list,使用.split()

>>> string_list.split('-') 
['5', '9', '7', '1', '7', '8', '3', '2', '4', '8', '7', '9']