Hi,
I'm a newbie to python and I'm reading a file and trying to split a string every 3 spaces, that is included any whitespace. string.split() will split the string up every whitespace, but is there another way to specify every 3 spaces, whether there is whitespace or not? I'm trying to do this example:
string = '491 43140113108107 11210'
and split it every 3 spaces. So I can pull out the numbers:
string = '491 43 140 113 108 107 11 210'

## All 5 Replies

You can do it like this.

``````>>> s = '491 43140113108107 11210'
>>> s
'491 43140113108107 11210'

>>> def splitCount(s, count):
return [''.join(x) for x in zip(*[list(s[z::count]) for z in range(count)])]

>>> a = splitCount(s, 3)
>>> a
['491', ' 43', '140', '113', '108', '107', ' 11', '210']
>>> b = ' '.join(a)
>>> b
'491  43 140 113 108 107  11 210'``````

Hi snippsatt,
When I do that for 'a' I get:

``````>>> a
['491', '431', '401', '131', '081', '071', '121', '061', '051', '381', '371', '021', '031', '041']
>>> b = ''.join(a)
>>> b
'491431401131081071121061051381371021031041'``````

But this means its splitting the numbers wrong, because where there is whitespace in front of a 2 digit number it has joined it to the next number.. The numbers should end up with:
'491', '43', '140', '113', '108', '107', '11', '210'
what am I doing wrong?

Take copy or type correct.
You have type wrong here. `b = ''.join(a) ---> b = ' '.join(a)` Rember space. `' '`

This worked for me:

``````>>> s = '491 43140113108107 11210'
>>> a=0
>>> b=3
>>> for x in s:
s1=s[a:b]
print(s1)
a+=3
b+=3``````

Result:

491
43
140
113
108
107
11
210

Thanks so much snippsat that works now :) Thanks sravan this looks a tiny bit easier due to my lack of knowledge of python.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.