英文:
How to split a string in python including whitespace?
问题
string = "this is a simple text"
result = ["this", " ", "is", " ", "a", " ", "simple", " ", "text"]
英文:
Final result should look like this:
string = "this is a simple text"
result = ["this", " ", "is", " ", "a", " ", "simple", " ", "text"]
答案1
得分: 2
一种方法是使用正则表达式进行分割并捕获分隔符:
import re
string = "this is a simple text"
re.split(r'(\s+)', string)
# ['this', ' ', 'is', ' ', 'a', ' ', 'simple', ' ', 'text']
注意,这与str.split()
在空字符串上的行为略有不同。
英文:
One way to do this would be to split with a regex and capture the delimiter:
import re
string = "this is a simple text"
re.split(r'(\s+)', string)
# ['this', ' ', 'is', ' ', 'a', ' ', 'simple', ' ', 'text']
Note, this will act a little different than str.split()
on an empty string.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论