Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting Python string into list of pairs

I have data in the following format:

"22.926 g 47.377 g 73.510 g 131.567 g 322.744 g"

What I would like to do is to split it into a list such that value and units are grouped together, e.g.:

["22.926 g","47.377 g","73.510 g","131.567 g","322.744 g"]

Of course, in Python 2.7, I can do this the hard way:

result = []
tokens = "22.926 g 47.377 g 73.510 g 131.567 g 322.744 g".split()
for index,item in enumerate(tokens[::2]):
    result.append(item+" "+tokens[index+1])

but I hoped that there is a slightly more elegant way for doing this?

like image 398
Andreas Avatar asked Apr 22 '26 23:04

Andreas


1 Answers

With regex (and the re.findall method)you could obtain what you need :

import re
text="22.926 g 47.377 g 73.510 g 131.567 g 322.744 g"
re.findall("\d+\.\d+ g", text)
>>>['22.926 g', '47.377 g', '73.510 g', '131.567 g', '322.744 g']

But keep in mind that when solving a problem with regex we often end with 2 problems ;)

like image 96
Cédric Julien Avatar answered Apr 24 '26 11:04

Cédric Julien