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?
The string strip() method in python is built-in from Python. It helps the developer to remove the whitespaces or specific characters from the string at the beginning and end of the string. Strip() method in string accepts only one parameter which is optional and has characters.
Python String strip() is an inbuilt function in the Python programming language that returns a copy of the string with both leading and trailing characters removed (based on the string argument passed).
The Python String strip() function works only on strings and will return an error if used on any other data type like list, tuple, etc.
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.
In this case, you might get some differences. Consider a line like:
"foo\tbar "
In this case, if you strip
, then you'll get {"foo":"bar"}
as the dictionary entry. If you don't strip, you'll get {"foo":"bar "}
(note the extra space at the end)
Note that if you use line.split()
instead of line.split('\t')
, you'll split on every whitespace character and the "strip
ing" will be done during splitting automatically. In other words:
line.strip().split()
is always identical to:
line.split()
but:
line.strip().split(delimiter)
Is not necessarily equivalent to:
line.split(delimiter)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With