String.strip() in Python

Rhs picture Rhs · Oct 22, 2012 · Viewed 273.2k times · Source

While learning about python, I came upon this code, which takes a text file, splits each line into an array, and inserts it into a custom dictionary, where the array[0] is the key and array[1] is the value:

my_dict = {}

infile = open("file.txt")
for line in infile:
    #line = line.strip() 
    #parts = [p.strip() for p in line.split("\t")]
    parts = [p for p in line.split("\t")]
    my_dict[parts[0]] = parts[1]
    print line

for key in my_dict:
    print "key: " + key + "\t" + "value " + my_dict[key]

I ran the program with the commented lines off and on and I got the same result. (of course replacing the second commented line with the line below it).It seems to me that doing a strip() is optional. Is it better practice to leave it in?

Answer

Martijn Pieters picture Martijn Pieters · Oct 22, 2012

If you can comment out code and your program still works, then yes, that code was optional.

.strip() with no arguments (or None as the first argument) removes all whitespace at the start and end, including spaces, tabs, newlines and carriage returns. Leaving it in doesn't do any harm, and allows your program to deal with unexpected extra whitespace inserted into the file.

For example, by using .strip(), the following two lines in a file would lead to the same end result:

 foo\tbar \n
foo\tbar\n

I'd say leave it in.