拆分 Python 字符串(句子)并附加空格

Split a Python string (sentence) with appended white spaces

是否可以拆分 Python 字符串(句子),使其在输出中保留单词之间的空格,但在拆分的子字符串中将其附加在每个单词之后?

例如:

given_string = 'This is my string!'
output = ['This ', 'is ', 'my ', 'string!']

也许这会有帮助?

>>> given_string = 'This is my string!'
>>> l = given_string.split(' ')
>>> l = [item + ' ' for item in l[:-1]] + l[-1:]
>>> l
['This ', 'is ', 'my ', 'string!']

只需拆分并添加白色space:

a = " "
output =  [e+a for e in given_string.split(a) if e]
output[len(output)-1] = output[len(output)-1][:-1]

最后一行是在thankyou之后删除space!

我大部分时间都避免使用正则表达式,但在这里它变得非常简单:

import re

given_string = 'This is my string!'
res = re.findall(r'\w+\W?', given_string)

# res ['This ', 'is ', 'my ', 'string!']