最近在看Python基礎教程的第一個項目,第一步就是將文件划分為所謂的block塊,然后依次進行處理。
而實例給出的兩段代碼並沒有看出直接的判斷空行或者類似的代碼,於是初步判斷strip方法是可以去除空行的。
以下是一個測試,測試文件使用的是和書里一樣的文本:
1 #!/usr/bin/env python 2 3 import sys 4 5 get = [] 6 7 for line in sys.stdin: 8 get.append(line) 9 10 print(get)
顯然讀取到了空行
1 #!/usr/bin/env python 2 3 import sys 4 5 get = [] 6 7 for line in sys.stdin: 8 get.append(line.strip()) 9 10 print(get)
顯然換行符已經被去掉了
所以strip的作用肯定不是像書上說的去除字符串兩端多余空格。
查了一下文檔說
Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace.
該函數的作用是去除字符串兩端多余的whitespace
The most common whitespace characters may be typed via the space bar or the tab key. Depending on context, a line-break generated by the return or enter key may be considered whitespace as well.
whitespace應該是空格,Tab和換行的統稱,而不僅僅是空格。