Cha*_*len -1 python split strip python-3.x
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)
Run Code Online (Sandbox Code Playgroud)
The result turns out to be:
b = ['1', '2', '3', '4', '5']
c = ['1', '2', '3', '4', '5']
Run Code Online (Sandbox Code Playgroud)
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?
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:
如果 sep 未指定或为 None,则应用不同的分割算法:连续的空格被视为单个分隔符,如果字符串具有前导或尾随空格,则结果将在开头或结尾不包含空字符串。因此,使用 None 分隔符分割空字符串或仅包含空格的字符串将返回 []。