我正在尋找一種方法來獲取一個字符串,並將其輸出爲每個字符拆分的列表?如何在python 2.7中保留空格來拆分這個字符串?
>>> sentence = 'hello I am cool'
>>> what_i_want(sentence)
['h', 'e', 'l', 'l', 'o', ' ', 'I', ' ', 'a', 'm', ' ', 'c', 'o', 'o', 'l']
然而,這似乎並沒有工作:
>>> sentence = 'hello I am cool'
>>> sentence = ' '.join(sentence).split()
>>> print sentence
['h', 'e', 'l', 'l', 'o', 'I', 'a', 'm', 'c', 'o', 'o', 'l']
它不會在之間打印空間!此外,這是行不通的:
>>> import re
>>> splitter = re.compile(r'(\s+|\S+)')
>>> sentence = 'hello I am cool'
>>> splitter.findall(sentence)
['hello', ' ', 'I', ' ', 'am', ' ', 'cool']
>>> sentence = ' '.join(sentence)
>>> splitter.findall(sentence)
['h', ' ', 'e', ' ', 'l', ' ', 'l', ' ', 'o', ' ', 'i', ' ', 'a', ' ', 'm', ' ', 'a', ' ', 'j']
任何人都可以告訴我一個高效和相對簡單的方法來做到這一點? 在此先感謝!
無需使用正則表達式。但是,這裏有一個使用正則表達式的解決方案:'re.findall('。',sentence)' – falsetru
謝謝大家回覆! +1 –