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
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.
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.
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.
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)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With