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

时间:2016-12-01 11:41:30

标签: python string python-3.x split position

示例:

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有没有办法做到这一点?

1 个答案:

答案 0 :(得分:5)

您可以re使用\S+模式来匹配非空白文本块,并访问m.group()m.start()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