-1

I have to split the values from a txt file. Problem is I can't split all the data and return. I don't even know which str method will accomplish my goal. Here's what I want to do:

Given data:

1.02.34.35.55.33.64.64.46.74.36.67.45.68.53.75.54.45.23.67.24.98.67.45.23.75.2

what I want:

1.0
2.3
4.3
5.5
.
.
.
.
.
5.2
Taha
  • 123
  • 1
  • 7

4 Answers4

3

chunk the string into groups of three, then re-join.

def chunks(l, n):
    """ Yield successive n-sized chunks from l.
    """
    for i in xrange(0, len(l), n):
        yield l[i:i+n]

s = '1.02.34.35.55.33.64.64.46.74.36.67.45.68.53.75.54.45.23.67.24.98.67.45.23.75.2'

print "\n".join(chunks(s,3))

Result:

1.0
2.3
4.3
5.5
...
5.2
Community
  • 1
  • 1
Kevin
  • 74,910
  • 12
  • 133
  • 166
2

Perhaps the easiest answer is to split the string up 3 characters at a time. This assumes that each number is exactly two digits with a decimal point in between.

>>> data = '1.02.34.35.55.33.64.64.46.74.36.67.45.68.53.75.54.45.23.67.24.98.67.45.23.75.2'
>>> [data[i:i+3] for i in range(0, len(data), 3)]
['1.0', '2.3', '4.3', '5.5', '5.3', '3.6', '4.6', '4.4', '6.7', '4.3', '6.6', '7.4', '5.6', '8.5', '3.7', '5.5', '4.4', '5.2', '3.6', '7.2', '4.9', '8.6', '7.4', '5.2', '3.7', '5.2']
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
1
s = '1.02.34.35.55.33.64.64.46.74.36.67.45.68.53.75.54.45.23.67.24.98.67.45.23.75.2'
for i in range(0,len(s),3):
    print(s[i:i+3])
tommy.carstensen
  • 8,962
  • 15
  • 65
  • 108
1

You could also use regexp.

import re
test='1.02.34.35.55.33.64.64.46.74.36.67.45.68.53.75.54.45.23.67.24.98.67.45.23.75.2'
num = re.compile('\d\.\d')
list_of_num = re.findall(num, test)

Internally it does the same thing - the regex engine matches against each character. So can't say this is more performant. You don't have to look at loops though.

Rcynic
  • 392
  • 3
  • 10