2

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

3
  • 3
    Are you able to provide your code attempts so we have a place to start? Commented Jun 30, 2011 at 15:25
  • for now my code is to read in the ouput from a bash command. the command is : rbox 100 D2, this produces the coordinates of 100 random points. now i'm stuck in formatting these ouputs. i use python subprocess to get the ouput Commented Jun 30, 2011 at 15:26
  • Then this might be a good place to start learning about string operations such as parsing: docs.python.org/library/string.html Commented Jun 30, 2011 at 15:28

5 Answers 5

6

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]
Sign up to request clarification or add additional context in comments.

1 Comment

oh, so you seem to have beaten me to this... by 3mins. +1
2

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']]

2 Comments

i'm totally overwhelmed by the quality and speed of the answers from stackoverflow... Thanks everyone
hah, yeah, I never do. but I'm not to creative when answering questions sometimes. I was trying to make this as logical and concise as possible.
0
points = []
for point in myStr.split('\n'):
    points.append(point.split())

Comments

0
a='x1 y1\n x2 y2\n x3 y3\n'

points = map (lambda x : x.split (), a.split ('\n'))

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.