如何在Python中拆分字符串,包括空格?

huangapple go评论65阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年5月25日 15:07:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76329696.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定