String strip in Python

0 votes
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?
Oct 22, 2018 in Python by ana1504.k
• 7,910 points
573 views

1 answer to this question.

0 votes
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
answered Oct 22, 2018 by SDeb
• 13,300 points

Related Questions In Python

0 votes
1 answer

Python Pandas: strip blank spaces in string in Index?

Yes, you can string the blank spaces ...READ MORE

answered May 14, 2019 in Python by Raj
2,576 views
0 votes
1 answer

Slice notation in Python for string reversal

The slice notation is [start:end:step]. Step = ...READ MORE

answered Apr 25, 2018 in Python by Nietzsche's daemon
• 4,260 points
470 views
0 votes
1 answer

Looping over a string in python

for c in "string": ...READ MORE

answered May 28, 2018 in Python by Nietzsche's daemon
• 4,260 points
440 views
0 votes
2 answers

Finding the index of a character in python string

You can use word.find('o') as well to ...READ MORE

answered Jun 1, 2018 in Python by george
• 200 points
1,237 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,023 views
0 votes
1 answer
0 votes
1 answer

Is there a string 'contains' in python?

In this case, you can use the ...READ MORE

answered Sep 25, 2018 in Python by SDeb
• 13,300 points
504 views
0 votes
1 answer

How do I append one string to another in Python?

If you only have one reference to ...READ MORE

answered Oct 22, 2018 in Python by SDeb
• 13,300 points
491 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP