String.strip() 重要性

String.strip() Importance

我的任务是编写一个函数,将文件中单词的长度与整数进行比较,然后 returns 所有具有该大小的单词。我得到的答案几乎相同,只是我没有像他们那样包含 string.strip():

def get_words(dictfile,size): words = []
  for word in open(dictfile).readlines():
      word = word.strip() #this is the only bit I didn't have in my own code
      if len(word) == size:
          words.append(word) 
  return words

离开 .strip() 真的会改变这个函数的输出,还是在处理文件时放入它只是一个好习惯?

编辑: 输入将是一个文件,其中每个单词都是一行,例如

a
abandon
abbey
abdominal

并且大小只是任意整数

它可能会产生影响,具体取决于您的输入。这意味着最好将它放在那里。

鉴于您每行阅读一个单词,strip() 存在以删除前导或尾随空格。例如:

word1
  word2
word3   

word2 将显示比没有 strip() 的其他长度更长的长度。这也适用于随后出现空格的情况,通过查看您的输入文件也更难发现(我什至找不到在这个答案中直观地表示它的好方法)

编辑: 正如@Two-Bit Alchemist 在评论中指出的那样, \n 字符也需要被剥离,否则你会遇到 off-by-1 错误。此字符用作行尾,因此我们人类通常不会注意到,但 Python 解释器会考虑到它。

def get_number_of_words(filename, size):
    words = []
    with open(filename) as dictfile:
        for line in dictfile:
            word = line.strip()
            if len(word) == size:
                words.append(word)
    return words

我用更多 "call-a-spade-a-spade" 变量名重写了您的函数,以弄清楚发生了什么。说说我替换的一些东西:

  • for word in open(dictfile).readlines():

通过以这种方式匿名打开文件,您已经丢弃了对文件 object 的引用,您将使用它来关闭它。此外,您不必要地使用 readlines 将整个文件读入内存。相反,我更喜欢 with 上下文管理器,它允许您保存对文件句柄的引用(使用 as),并在您完成后自动关闭文件,这是您忽略的。 (技术上 Python 最终会为你做这件事,但这仍然是一个好习惯。)

另请注意,我直接遍历文件 for line in dictfile——这比 front-loading 将整个文件放入内存要高效得多。


至于你的标题问题,如果你希望这个函数提供准确的计数,那么在这里调用 line.strip() 是绝对必要的。您迭代的文件中的每一行都包含一个 '\n' 字符(换行符),该字符按 len 计数,因为它是字符串的一部分。如您所见,如果您询问函数文件中有多少个长度为 4 的单词,它会为您提供所有长度为 3 的单词(第 4 个字符是 '\n',人类通常不会数) .

在@Knells 回答的基础上再添加一些要点, String.Strip() 函数不仅用于在 none 作为 strip 的参数提供时删除尾随空格,它还可以删除您指定为的任何字符或字符列表来自 end 和 beginning 的参数例如字符串

str1 = " Saltharion   "
//will result in "Saltharion"
str1.Strip() 

str2 = "ooHow are yuoo"
// Will result in "How are yu", here the char "o" at the `end and beginning` is stripped from string
str2.strip("o") 

str3 = "ar How are you, I am good are" 
// will result in "How are you, I am good", here it will not strip occurrence of "are" it will strip occurrence of "a" "r" "e" from end and beginning
str3.strip("are")

请查看文档 here