Splitting a string by list of indices

后端 未结 3 500
说谎
说谎 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: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']
    

提交回复
热议问题