Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

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?

1 Answer

0 votes
by (106k points)

In, Python String.strip() with no arguments removes all whitespace at the start and end, including spaces, tabs, newlines and carriage returns. 

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

To know more about this you can have a look at the following video tutorial:-

 

Related questions

0 votes
2 answers
0 votes
1 answer
asked Oct 3, 2019 in Python by Sammy (47.6k points)
0 votes
4 answers
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...