Search code examples
pythonstringfilestrip

String.strip() Importance


I had the task of writing a function that compares the length of the words in a file to an integer and then returns all the words that are that size. The answer I got was almost identical except I didn't include a string.strip() like they did:

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

Would leaving the .strip() out really change the output of this function or is it just good practice to put it in when working with files?

EDIT: The input would be a file where every word is one a single line e.g.

a
abandon
abbey
abdominal

and the size is just any integer


Solution

  • It might have an effect depending on your input. Meaning it is probably best to have it in there.

    Given you are reading one word per line, the strip() exists to remove leading or trailing whitespace. E.G.:

    word1
      word2
    word3   
    

    word2 will show a greater length than the others without strip(). This also applies if the whitespaces come afterwards, which is also much harder to spot by looking at your input file (I can't even find a good way to represent it visually in this answer)

    Edit: As @Two-Bit Alchemist pointed out in the comments the \n character needs to be stripped also otherwise you have an off-by-1 error. This character is used as a line ending so isn't usually noticed by us humans, but the Python interpreter takes it into account.