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)
-regexp替换组;将非空格\S+\S+
和空格\S+
字符序列捕获为结果列表的单独项\S+