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)]
Answer from eumiro on Stack Overflows = '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)]
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.
I googled those ['python split string at index', 'python regex split string at index'], and i couldn't find what i wanted.
This is what i want:
Example 1:
number = '8471923' values = ['8', '471', '923']
Example 2:
number = '7013' values = ['7', '013']
EDIT: i tried this but it doesn't work.
number = '7013' values = [number[:3], number[3:6], number[6:9]] print(values) # out: ['701', '3', '']
EDIT: I was trying to solve this kata and here is my final code, but guess what, i did it the other way around, i had to convert 'twenty' to 20, but i'm converting 20 to 'twenty' :D.
Anyway thanks all, this f'{number:_}'.split('_') solved my problem.
How do I split a list every 2 indexes
How can i split a string at index?
Using Split only on the first occurrence of a character?
Why does re.split cause first index to be empty string?
Hello I have a list of integers:
trackIndex = [0, 22, 23, 58, 59,79,80,100,101,122]
These serve as indexes for another list of strings from a text file and I only need to extract certain indexes.
strings = [ "sentence 1", "sentence 2","sentence 3","sentence 4"....]
How can I loop through trackIndex and split it every two indexes (i.e. [0,22], [23,58],[59,79],[80, 100], [101,122] and then take those to extract those indexes from the "strings list" and store it in a new list called "newList"?