分割字符串的最佳方式是什么
text = "hello there how are you"
在 Python 中?
所以我最终会得到这样的数组:
['hello there', 'there how', 'how are', 'are you']
我试过这个:
liste = re.findall('((\S+\W*){'+str(2)+'})', text)
for a in liste:
print(a[0])
但是我得到:
hello there
how are
you
如何让 findall 函数在搜索时只移动一个标记?
请您参考如下方法:
这是一个使用 re.findall 的解决方案:
>>> import re
>>> text = "hello there how are you"
>>> re.findall(r"(?=(?:(?:^|\W)(\S+\W\S+)(?:$|\W)))", text)
['hello there', 'there how', 'how are', 'are you']
查看 re 的 Python 文档:https://docs.python.org/3/library/re.html
(?=...)前瞻断言(?:...)非捕获正则括号
