seeker
seeker

Reputation: 558

What is the reason for the differences in how this string is split?

I am using the str.split() method and I can pin down what causes the difference in result, but I don't understand why it is.

>>> dummy_line = "Line1 \nLine2 \nLine3"
>>> print(dummy_line.split())
['Line1', 'Line2', 'Line3']

>>> print(str.split(" "))
['Line1', '\nLine2', '\nLine3']

Why does defining the split delimeter as " " in the second instance result in the returned lines including the new line escape character \n?

Upvotes: 0

Views: 52

Answers (2)

OneCricketeer
OneCricketeer

Reputation: 191738

str.split(" ") separates on a single space. Newlines therefore are kept.

str.split() breaks all whitespace. (\s, \r, \n, \t)

Maybe your misunderstanding is Python's support for default function arguments?

Hint: Try dummy_line = "Line 1\nLine 2"

Upvotes: 3

thangtn
thangtn

Reputation: 876

  • split() - strip all the white space characters for you - off course including the '\n'
  • split(" ") - strip exactly one white space for you.

Upvotes: 0

Related Questions