James Franco James Franco - 4 months ago 9
Python Question

what does this statement (line, str) = str.split("\n", 1) mean?

I am familiar with the split function and i would use it as such

str = "Line1-abcdef \nLine2-abc \nLine4-abcd";
print str.split( )


The above would return this

['Line1-abcdef', 'Line2-abc', 'Line4-abcd']


Simple and easy however I came across a piece of code that has this statement

(line, str) = str.split("\n", 1)


There are two things that I dont understand here

1)The second paremeter of split and what that does. I looked here and it says the number of lines made what does that mean ?

2)split returns an iterable vector why is it being assigned to
(line,str)
? What does
(line , str)
mean here

Answer

The second argument maxsplit=1 means stop splitting after you meet the separator \n once.

Therefore you have only two parts, your line and the rest of the string. You should really take a look at examples, starting here


For example:

str = 'This is one line\nThis is a second line\nThis is a third line'
(line, str) = str.split('\n', 1)
print(line)
# 'This is one line'
print(str)
# 'This is a second line\nThis is a third line'
Comments