Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string by count of characters

Tags:

python

string

I can't figure out how to do this with string methods:

In my file I have something like 1.012345e0070.123414e-004-0.1234567891.21423... which means there is no delimiter between the numbers.

Now if I read a line from this file I get a string like above which I want to split after e.g. 12 characters. There is no way to do this with something like str.split() or any other string method as far as I've seen but maybe I'm overlooking something?

Thx

like image 627
BandGap Avatar asked Aug 18 '11 16:08

BandGap


People also ask

How do you split text by character count?

Ensure the column is a text data type. Select Home > Split Column > By Number of Characters. The Split a column by Number of Characters dialog box appears. In the Number of characters textbox, enter the number of characters used to split the text column.

How do you split a string in Python with number of characters?

Python String split() MethodThe split() method splits a string into a list. You can specify the separator, default separator is any whitespace.

How can I split a string into segments of N characters in Java?

Using the String#split Method As the name implies, it splits a string into multiple parts based on a given delimiter or regular expression. As we can see, we used the regex (? <=\\G. {” + n + “}) where n is the number of characters.


2 Answers

Since you want to iterate in an unusual way, a generator is a good way to abstract that:

def chunks(s, n):     """Produce `n`-character chunks from `s`."""     for start in range(0, len(s), n):         yield s[start:start+n]  nums = "1.012345e0070.123414e-004-0.1234567891.21423" for chunk in chunks(nums, 12):     print chunk 

produces:

1.012345e007 0.123414e-00 4-0.12345678 91.21423 

(which doesn't look right, but those are the 12-char chunks)

like image 106
Ned Batchelder Avatar answered Sep 22 '22 16:09

Ned Batchelder


You're looking for string slicing.

>>> x = "1.012345e0070.123414e-004-0.1234567891.21423" >>> x[2:10] '012345e0' 
like image 24
J.J. Avatar answered Sep 21 '22 16:09

J.J.