2014-09-18 43 views
0

通常我會使用string.stripmap一起去除字符串列表中的空格。 string是已棄用的模塊。 Pylint和谷歌風格指南建議不要使用它。將字符串串起來的最佳方式是什麼?string.strip的替代

>>> import string 
>>> s = ['a', ' b', 'c ', ' d '] 
>>> print map(string.strip, s) 
['a', 'b', 'c', 'd'] 
>>> 
+0

...並且map是python 3中的一個生成器,因此您需要做出更多更改。 – tdelaney 2014-09-18 22:19:56

回答

2

split現在是一種字符串方法。 map很容易替換爲listgenerator的理解。

print([i.strip() for i in s]) 
+0

@PeterDeGlopper該語法適用於2.x和3.x.如果要打印多個內容或使用關鍵字參數,則只需要擔心放棄括號。儘管你應該在2.x中使用'from __future__ import print_function'。 – 2014-09-18 21:49:01

+0

沒有必要放棄'map',它甚至沒有被移出到'functools'。 – jonrsharpe 2014-09-18 21:49:09

+0

@jonrsharpe我覺得''str.strip'與'map'不太直觀,所以我通常會推薦list或generator的理解。理解也適用於你的輸入是'bytes'還是'str',它可以是一個有用的或危險的功能。 – 2014-09-18 21:51:15

2

strip也是strunicode內建類型的方法。因此,只需將未綁定方法傳遞給map即可:map(str.strip, s)