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 toge
Solution 1:
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 ;)
Solution 2:
a = "22.926 g 47.377 g 73.510 g 131.567 g 322.744 g".split()
c = [" ".join((v, g)) for v,g in zip(a[:-1:2], a[1::2])]
Solution 3:
what about splitting according to " g"
and strip/filter out empty fields, re-add the g
suffix afterwards, in one line:
["{} g".format(x.strip()) for x in"22.926 g 47.377 g 73.510 g 131.567 g 322.744 g".split(" g") if x]
result:
['22.926 g', '47.377 g', '73.510 g', '131.567 g', '322.744 g']
Solution 4:
In one-line! Split the string, and use list comprehension to get the desired output by removing all g
and appending g
!
s="22.926 g 47.377 g 73.510 g 131.567 g 322.744 g"
>>> [x+' g'forx in s.split() ifx!='g']
Output
['22.926 g', '47.377 g', '73.510 g', '131.567 g', '322.744 g']
Solution 5:
data = "22.926 g 47.377 g 73.510 g 131.567 g 322.744 g"sep = 'g'result = ['{digit} {sep}'.format(digit=d.strip(), sep=sep) for d in data[:-1].split(sep)]
Post a Comment for "Splitting Python String Into List Of Pairs"