如何将字符串分成单词和空格?

时间:2018-10-25 12:57:54

标签: python string split

我想分割string = ['O little forests,'],以便输出同时包含单词和空格,并在最后一个单词后附加最后一个逗号。所需的输出如下所示:

output = ['O', ' ', 'little', ' ', 'forests,']

我能够使用line.split()将给定的字符串拆分为单词列表,并排除空格。欢迎您提出建议!

4 个答案:

答案 0 :(得分:3)

您可以使用groupby

from itertools import groupby

sentence = 'O little forests'

result = [''.join(v) for k, v in groupby(sentence, key=str.isspace)]
print(result)

输出

['O', ' ', 'little', ' ', 'forests']

答案 1 :(得分:2)

您可以使用re(正则表达式):

import re

sentence = 'O little forests'

re.split("( )", sentence) # ['O', ' ', 'little', ' ', 'forests']

答案 2 :(得分:2)

您可以使用re进行此工作,如以下代码所示。

import re
string = ['O little forests'] 
for a  in string:
  print(re.split(r'(\s+)', a))

输出:

['O', ' ', 'little', ' ', 'forests']

答案 3 :(得分:0)

您可以在列表理解中像这样在每个单词之间添加一个空格元素:

s = 'O little forest'
# puts ' ' element after each word.
st = [k for j in [[e, ' '] for e in s.split()] for k in j]
st.pop() # drop last.
st
>>> ['O', ' ', 'little', ' ', 'forest']