通常我會使用string.strip
與map
一起去除字符串列表中的空格。 string
是已棄用的模塊。 Pylint和谷歌風格指南建議不要使用它。將字符串串起來的最佳方式是什麼?string.strip的替代
>>> import string
>>> s = ['a', ' b', 'c ', ' d ']
>>> print map(string.strip, s)
['a', 'b', 'c', 'd']
>>>
通常我會使用string.strip
與map
一起去除字符串列表中的空格。 string
是已棄用的模塊。 Pylint和谷歌風格指南建議不要使用它。將字符串串起來的最佳方式是什麼?string.strip的替代
>>> import string
>>> s = ['a', ' b', 'c ', ' d ']
>>> print map(string.strip, s)
['a', 'b', 'c', 'd']
>>>
@PeterDeGlopper該語法適用於2.x和3.x.如果要打印多個內容或使用關鍵字參數,則只需要擔心放棄括號。儘管你應該在2.x中使用'from __future__ import print_function'。 – 2014-09-18 21:49:01
沒有必要放棄'map',它甚至沒有被移出到'functools'。 – jonrsharpe 2014-09-18 21:49:09
@jonrsharpe我覺得''str.strip'與'map'不太直觀,所以我通常會推薦list或generator的理解。理解也適用於你的輸入是'bytes'還是'str',它可以是一個有用的或危險的功能。 – 2014-09-18 21:51:15
strip
也是str
和unicode
內建類型的方法。因此,只需將未綁定方法傳遞給map
即可:map(str.strip, s)
...並且map是python 3中的一個生成器,因此您需要做出更多更改。 – tdelaney 2014-09-18 22:19:56