Reputation: 5901
I have a python string in the following format:
"x1 y1\n x2 y2\n x3 y3\n ..."
I would like to transform this into a list points = [p1, p2, p3,...]
, where p1
, p2
and p3
are [x1,y1]
, [x2,y2]
and [x3,y3]
etc.
Thanks
Upvotes: 2
Views: 1346
Reputation: 19645
obviously, many ways to do this.
I would use list comprehension for its brevitiy.
>>> str = 'x1 y1\n x2 y2\n x3 y3\n'
>>> [p.split() for p in str.split('\n') if p != '']
[['x1', 'y1'], ['x2', 'y2'], ['x3', 'y3']]
Upvotes: 2
Reputation: 4673
Would this do?
>>> raw = "x1 y1\nx2 y2\nx3 y3"
>>> lines = raw.split("\n")
>>> points = []
>>> for l in lines:
... points.append(l.split(' '))
...
>>> points
[['x1', 'y1'], ['x2', 'y2'], ['x3', 'y3']]
>>>
Split on new lines, then for each line assume a space splits the values, create a list of points from that.
Upvotes: 0
Reputation: 32429
a='x1 y1\n x2 y2\n x3 y3\n'
points = map (lambda x : x.split (), a.split ('\n'))
Upvotes: 0
Reputation: 113945
points = []
for point in myStr.split('\n'):
points.append(point.split())
Upvotes: 0
Reputation: 29103
Think you can use the following:
inputText = "x1 y1\n x2 y2\n x3 y3\n"
print [line.split() for line in inputText.split('\n') if line]
Upvotes: 6