Python: splitting a long string in separate places in a single pass

I am completely new to programming and only yesterday began to study python for scientific purposes.

Now I would like to split one very long line (174 characters) into several smaller ones, as shown below:

string = 'AA111-99XYZ ' split = ('AA', 11, 1, -99, 'XYZ') 

Right now, the only thing I can think of is to use the slice x-times syntax, but maybe there is a more elegant way? Is there a way to use a list of integers to indicate split positions, for example.

 split_at = (2, 4, 5, 8, 11) split = function(split_at, string) 

I hope my question is not too stupid - I could not find a similar example, but maybe I just do not know what I'm looking for?

Thanks,

Jan

+4
source share
4 answers

Like this:

 >>> string = 'AA111-99XYZ ' >>> split_at = [2, 4, 5, 8, 11] >>> [string[i:j] for i, j in zip([0]+split_at, split_at+[None])] ['AA', '11', '1', '-99', 'XYZ', ' '] 
+3
source
 def split_string(string, points): for left, right in zip(points, points[1:]): yield string[left:right] 
+1
source

to avoid redundancy, you can use the good ATOzTOA solution and put it in the lamba function:

 st = 'AA111-99XYZ ' sa = [2, 4, 5, 8, 11] res = lambda string,split_at:[string[i:j] for i, j in zip([0]+split_at, split_at+[None])] print(res(st,sa)) 
0
source

Being relatively new to Python on my own, I took a beginner's beginner approach here to help guide someone who is not familiar with the power of Python.

 string = 'AA111-99XYZ ' split_at = [2, 4, 5, 8, 11] for i in range(len(split_at)): if i == 0: print string[:split_at[i]] if i < len(split_at)-1: print string[split_at[i]:split_at[i+1]] if i == len(split_at)-1: print string[split_at[i]:] 
0
source

All Articles