Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a string by list of indices

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:

s = 'long string that I want to split up' indices = [0,5,12,17] parts = [s[index:] for index in indices] for part in parts:     print part 

This will return:

long string that I want to split up
string that I want to split up
that I want to split up
I want to split up

I'm trying to get:

long
string
that
I want to split up

like image 787
Yarin Avatar asked Jun 01 '12 13:06

Yarin


People also ask

Can you split a string at an index?

To split a string at a specific index, use the slice method to get the two parts of the string, e.g. str. slice(0, index) returns the part of the string up to, but not including the provided index, and str. slice(index) returns the remainder of the string.

How do you split a string into a list of elements?

The split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.

How do you split a word by index in Python?

In Python, strings can be broken and accessed using a split() function, which splits the given string according to the specified separator or by default separator as whitespace. This function returns the array of strings, so as earlier in Python array can be accessed using indexing.


1 Answers

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)] 
like image 80
eumiro Avatar answered Oct 12 '22 01:10

eumiro