Reputation: 71
I'd like to split a string = ['O little forests,']
so that the output includes both words and spaces, with the last comma appended to the last words. Here's what the desired output should look like:
output = ['O', ' ', 'little', ' ', 'forests,']
I was able to split the given string into a list of words with spaces excluded by using line.split()
. I welcome your suggestions!
Upvotes: 3
Views: 190
Reputation: 2950
You may do this work using re
like following code.
import re
string = ['O little forests']
for a in string:
print(re.split(r'(\s+)', a))
Output:
['O', ' ', 'little', ' ', 'forests']
Upvotes: 2
Reputation: 379
You can use re (regex):
import re
sentence = 'O little forests'
re.split("( )", sentence) # ['O', ' ', 'little', ' ', 'forests']
Upvotes: 2
Reputation: 5958
You can add a space element between each word like this in a list comprehension:
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']
Upvotes: 0
Reputation: 61910
You could use groupby:
from itertools import groupby
sentence = 'O little forests'
result = [''.join(v) for k, v in groupby(sentence, key=str.isspace)]
print(result)
Output
['O', ' ', 'little', ' ', 'forests']
Upvotes: 3