Splitting a string by list of indices
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)]
How to split string by list of Indexes python?
Here's a version using a list comprehension:
In [42]: s = "Hello there!"
In [43]: [s[v1:v2] for v1, v2 in zip([0]+l, l+[None])]
Out[43]: ['He', 'llo ', 'the', 're!']
Split python string by predifned indices
Like this?
>>> map(lambda x: test_string[slice(*x)], zip(split_points, split_points[1:]+[None]))
['the', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
We're zip
ing split_points
with a shifted self, to create a list of all consecutive pairs of slice indexes, like [(0,3), (3,8), ...]
. We need to add the last slice (32,None)
manually, since zip
terminates when the shortest sequence is exhausted.Then we map
over that list a simple lambda slicer. Note the slice(*x)
which creates a slice
object, e.g. slice(0, 3, None)
which we can use to slice the sequence (string) with standard the item getter (__getslice__
in Python 2).
A little bit more Pythonic implementation could use a list comprehension instead of map
+lambda
:
>>> [test_string[i:j] for i,j in zip(split_points, split_points[1:] + [None])]
['the', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
How to split a python string based on indices?
i think something like this is what you are looking for
line = "I would like a hamburger"
lst = line.split()
for index, word in enumerate(lst):
print(lst[index-2:index],lst[index+1:index+3])
Split a list into sub-lists based on index ranges
Note that you can use a variable in a slice:
l = ['a',' b',' c',' d',' e']
c_index = l.index("c")
l2 = l[:c_index]
This would put the first two entries of l in l2 String split with indices in Python
I think it's more natural to return the start and end of the corresponding splices. eg (0, 4) instead of (0, 3)
>>> from itertools import groupby
>>> def splitWithIndices(s, c=' '):
... p = 0
... for k, g in groupby(s, lambda x:x==c):
... q = p + sum(1 for i in g)
... if not k:
... yield p, q # or p, q-1 if you are really sure you want that
... p = q
...
>>> a = "This is a sentence"
>>> list(splitWithIndices(a))
[(0, 4), (5, 7), (8, 9), (10, 18)]
>>> a[0:4]
'This'
>>> a[5:7]
'is'
>>> a[8:9]
'a'
>>> a[10:18]
'sentence'
how to split string by multi lengths?
Try this:
def split(s, len_arr):
res = []
start = 0
for part_len in len_arr:
res.append(s[start:start+part_len])
start += part_len
return res
> split("294216673539910447", [3, 2, 3, 3, 2, 2, 3])
> ['294', '21', '667', '353', '99', '10', '447']
Related Topics
Reading Binary Data from Stdin
Why Python Has Limit for Count of File Handles
Cartesian Product of a Dictionary of Lists
Regex for Existence of Some Words Whose Order Doesn't Matter
How to Group a Pandas Dataframe by a Defined Time Interval
Pip Is Not Able to Install Packages Correctly: Permission Denied Error
How to Ignore One Single Specific Line with Pylint
Python Regex to Find a String in Double Quotes Within a String
How to Align Gridlines for Two Y-Axis Scales Using Matplotlib
Slicing a List into N Nearly-Equal-Length Partitions
How to Convert Datetime.Timedelta to Minutes, Hours in Python
Overflowerror: (34, 'Result Too Large')
Change to Sudo User Within a Python Script