Python 在单词的开头和结尾拆分字符串

Python 在单词的开头和结尾拆分字符串,python,split,Python,Split,我有这样一个字符串: "hello world foo bar" ["hello", " ", "world", " ", "foo", " ", "bar"] 我想在单词的开头和结尾分开,就像这样: "hello world foo bar" ["hello", " ", "world", " ", "foo", " ", "bar"] 使用re.split()函数: import re s = 'hello world foo bar' result

我有这样一个字符串:

"hello world   foo  bar"
["hello", " ", "world", "   ", "foo", "  ", "bar"]
我想在单词的开头和结尾分开,就像这样:

"hello world   foo  bar"
["hello", " ", "world", "   ", "foo", "  ", "bar"]
使用
re.split()
函数:

import re

s = 'hello world   foo  bar'
result = re.split(r'(\s+)', s)
print(result)
result = re.findall(r'\S+|\s+', s)
输出:

['hello', ' ', 'world', '   ', 'foo', '  ', 'bar']
  • (\s+
    )-在
    re.split()函数模式中使用时,按模式
    \s+
    的出现次数(一个或多个空格字符)拆分输入字符串。如果模式中使用了捕获括号
    (…)
    ,则模式中所有组的文本也将作为结果列表的一部分返回


或与
re.findall()
函数相同的结果:

import re

s = 'hello world   foo  bar'
result = re.split(r'(\s+)', s)
print(result)
result = re.findall(r'\S+|\s+', s)
  • \S+\S+
    -regexp替换组;将非空格
    \S+
    和空格
    \S+
    字符序列捕获为结果列表的单独项

你试过了吗。。有什么吗?我肯定OP可以复制粘贴那个,但它并没有教会他们任何东西。@Blorgbeard,你有我的解释