Search code examples
pythonstringpython-3.xsplitposition

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


Example:

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

How can I create a list adding the string position of the elements before the splitting:

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

Is there a way in Python to do this?


Solution

  • You may use re with the \S+ pattern to match non-whitespace chunks of text and access m.group(), m.start() and m.end() to collect the necessary data:

    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]]
    

    See this Python demo