What Is the Difference Between Input(). Strip(). Split() and Input(). Split()? [Duplicate]

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

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
James H. Sterling

James H. Sterling

Environmental Science & Climate Journalist

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.

Share this article
Twitter Facebook Pinterest