如何拆分字符串并在拆分前添加元素的字符串位置?

How to split string and add string positions of elements before the split?

示例:

s="  300       january      10       20     " 
mylist = s.split()
mylist = ['300', 'january', '10', '20']

如何创建一个列表,在拆分之前添加元素的字符串位置:

mylistStringPos = [['300',startpos:endpos],...] 
mylistStringPos = [['300',2:5], '['january',12:19]', '['10',25:27]', '['20',34:36]']]

Python 有办法做到这一点吗?

您可以使用 re\S+ 模式来匹配非空白文本块并访问 m.group(), m.start() and m.end() 以收集必要的数据:

import re
s="  300       january      10       20     "
print([[x.group(), x.start(), x.end()] for x in re.finditer(r'\S+', s)])
# => [['300', 2, 5], ['january', 12, 19], ['10', 25, 27], ['20', 34, 36]]

this Python demo