如何在 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']

谁能告诉我一种有效且相对简单的方法来做到这一点?提前感谢!

将字符串传递给list,您将获得单字符字符串的列表。

>>> sentence = 'hello I am cool'
>>> list(sentence)
['h', 'e', 'l', 'l', 'o', ' ', 'I', ' ', 'a', 'm', ' ', 'c', 'o', 'o', 'l']

使用 list()

>>> list(sentence)
['h', 'e', 'l', 'l', 'o', ' ', 'I', ' ', 'a', 'm', ' ', 'c', 'o', 'o', 'l']

如果要迭代每个字符,还可以对字符串使用for循环。

for chr in 'hello I am cool':
    print(chr)

它应该导致:

h
e
l
l
o
I
a
m
c
o
o
l

最新更新