-1

Split() function uses whitespace string as separator and removes the empty strings, so I think there is no use using strip() or rstrip() function to remove extra whitespace in head or tail. And here is my example:

a = ' \n   1 2 3 4     \n\n 5 \n\n \t'
b = a.rstrip().split()
c = a.split()
print('b =',b)
print('c =',c)

The result turns out to be:

b = ['1', '2', '3', '4', '5']
c = ['1', '2', '3', '4', '5']

It seems that there is no difference in betweeen. However, the former one( intput().strip().split()) seems more widely used. So what is the difference in these two expressions?

0

1 Answer 1

6

There's no difference. split() ignores whitespace on the ends of the input by default. People call strip() first either because they think it's clearer or because they don't know this behavior of split().

Docs:

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns [].

3
  • 1
    As a side note, this is not clearly documented for Python 2, hence the confusion: docs.python.org/2/library/string.html#string.split
    – Selcuk
    Dec 14, 2018 at 0:50
  • @Selcuk: Yup, I'd probably call strip() too if I'd only seen those docs. Dec 14, 2018 at 0:52
  • There's no difference in the output if you use the default parameters for .strip() and .split(), but that will not always be the case. Compare these examples: a = ' \n 1,2,3,4,5 \n\n \t' b = a.strip().split(',') c = b.split(',') print(b) # Out: ['1', '2', '3', '4', '5'] print(c) # Out: [' \n 1', '2', '3', '4', '5 \n\n \t'] Also, while just using .split() is a useful shortcut, .strip().split() more clearly explains what is happening.
    – ajrwhite
    Dec 14, 2018 at 0:58

Not the answer you're looking for? Browse other questions tagged or ask your own question.