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
a, b, c = s.split('\n\n')
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
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.
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.
精彩评论