input().strip().split() 和 input().split() 有什么区别?

What is the difference between input().strip().split() and input().split()?

Split() 函数使用空白字符串作为分隔符并删除空字符串,所以我认为使用 strip() 或 rstrip() 函数删除头部或尾部的额外空白是没有用的。这是我的例子:

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)

结果是:

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

看起来两者之间没有区别。然而,前者(intput().strip().split())似乎使用更广泛。那么这两种表达方式有什么区别呢?

没有区别。 split() 默认情况下忽略输入末尾的空格。人们首先调用 strip() 要么是因为他们认为它更清楚,要么是因为他们不知道 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 [].