2024-03-29 06:44:51 发布
网友
我有这样一根线:
"hello world foo bar"
我想在单词的开头和结尾分开,像这样:
["hello", " ", "world", " ", "foo", " ", "bar"]
使用re.split()函数:
re.split()
import re s = 'hello world foo bar' result = re.split(r'(\s+)', s) print(result)
输出:
['hello', ' ', 'world', ' ', 'foo', ' ', 'bar']
(\s+)
\s+
(...)
https://docs.python.org/3.6/library/re.html?highlight=re#re.split
或与re.findall()函数相同的结果:
re.findall()
result = re.findall(r'\S+|\s+', s)
\S+|\s+
\S+
使用
re.split()
函数:输出:
(\s+)
-在re.split()
函数模式中使用时,按模式\s+
(一个或多个空格字符)的出现次数拆分输入字符串。如果捕获括号(...)
用于模式中,那么模式中所有组的文本也将作为结果列表的一部分返回https://docs.python.org/3.6/library/re.html?highlight=re#re.split
或与
re.findall()
函数相同的结果:\S+|\s+
-regexp alternation组;捕获非空格\S+
和空格\s+
字符序列作为结果列表的独立项相关问题 更多 >
编程相关推荐