Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.strip() in Python

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?

like image 698
Rhs Avatar asked Oct 22 '12 14:10

Rhs


People also ask

What is string Strip in Python?

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.

Is Strip a string function?

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).

Does Strip () return a list?

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.


2 Answers

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.

like image 104
Martijn Pieters Avatar answered Sep 22 '22 22:09

Martijn Pieters


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 "striping" 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) 
like image 37
mgilson Avatar answered Sep 20 '22 22:09

mgilson