views:

94

answers:

4

Hi there,

I have a piece of text that gets handed to me like:

here is line one\n\nhere is line two\n\nhere is line three

What I would like to do is break this string up into three separate variables. I'm not quite sure how one would go about accomplishing this in python.

Thanks for any help, jml

+4  A: 
a, b, c = s.split('\n\n')
Ignacio Vazquez-Abrams
it looks like this turns s into a list element. how can i index into it?
jml
It does not modify `s`. Strings are immutable, so string operations return a new object.
Ignacio Vazquez-Abrams
cool. figured out what you were actually suggesting. :p thanks!
jml
A: 

To break it into a list with 3 elements:

mystring = "here is line one\n\nhere is line two\n\nhere is line three"
listofthings = mystring.split("\n\n")

Then you can access them with listofthings[0], listofthings[1], and listofthings[2].

To put them in separate actual variables:

mystring = "here is line one\n\nhere is line two\n\nhere is line three"
a,b,c = mystring.split("\n\n")

# a now contains "here is line one", et cetera.
Amber
`mystring.split()` is going to split on the whitespaces and the endlines.
tdedecko
Whoops, you're right. That's what I get for posting right after waking up. Fixed.
Amber
+1  A: 
s1, s2, s3 = that_string_variable.split('\n\n')

Basically, whatever variable you've got that string in, you then .split() on the token you want to use as the separator (in this case, '\n\n'), and that will return a list of strings. You can assign using "unpacking" where you specify multiple variables for each of the elements to go to. An assignment like above says "I know the right hand side will give me three elements, and I want those to go into s1, s2, and s3 in that order.

Daniel DiPaolo
+1  A: 

You can use the split function:

s = 'ab\n\ncd'
tokens = s.split('\n\n')

Then tokens is the array ['ab', 'cd']

EDIT: I assumed you meant that you want your example to be split into 3 strings, but in general to split the string > 3 strings if necessary

Il-Bhima