[英]How to split a string into words and spaces?
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. 我想分割一个
string = ['O little forests,']
以便输出包括单词和空格,最后一个逗号附加到最后一个单词。 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()
. 我能够将给定的字符串拆分为使用
line.split()
排除空格的单词列表。 I welcome your suggestions! 我欢迎你的建议!
You can use re (regex): 你可以使用re(正则表达式):
import re
sentence = 'O little forests'
re.split("( )", sentence) # ['O', ' ', 'little', ' ', 'forests']
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']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.