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?
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 ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With