Splitting a string by list of indices

后端 未结 3 486
说谎
说谎 2020-11-29 06:11

I want to split a string by a list of indices, where the split segments begin with one index and end before the next one.

Example:

         


        
相关标签:
3条回答
  • 2020-11-29 06:26

    Here is a short solution with heavy usage of the itertools module. The tee function is used to iterate pairwise over the indices. See the Recipe section in the module for more help.

    >>> from itertools import tee, izip_longest
    >>> s = 'long string that I want to split up'
    >>> indices = [0,5,12,17]
    >>> start, end = tee(indices)
    >>> next(end)
    0
    >>> [s[i:j] for i,j in izip_longest(start, end)]
    ['long ', 'string ', 'that ', 'I want to split up']
    

    Edit: This is a version that does not copy the indices list, so it should be faster.

    0 讨论(0)
  • 2020-11-29 06:38

    You can write a generator if you don't want to make any modifications to the list of indices:

    >>> def split_by_idx(S, list_of_indices):
    ...     left, right = 0, list_of_indices[0]
    ...     yield S[left:right]
    ...     left = right
    ...     for right in list_of_indices[1:]:
    ...         yield S[left:right]
    ...         left = right
    ...     yield S[left:]
    ... 
    >>> 
    >>> 
    >>> s = 'long string that I want to split up'
    >>> indices = [5,12,17]
    >>> [i for i in split_by_idx(s, indices)]
    ['long ', 'string ', 'that ', 'I want to split up']
    
    0 讨论(0)
  • 2020-11-29 06:41
    s = 'long string that I want to split up'
    indices = [0,5,12,17]
    parts = [s[i:j] for i,j in zip(indices, indices[1:]+[None])]
    

    returns

    ['long ', 'string ', 'that ', 'I want to split up']
    

    which you can print using:

    print '\n'.join(parts)
    

    Another possibility (without copying indices) would be:

    s = 'long string that I want to split up'
    indices = [0,5,12,17]
    indices.append(None)
    parts = [s[indices[i]:indices[i+1]] for i in xrange(len(indices)-1)]
    
    0 讨论(0)
提交回复
热议问题