Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does 'if x.strip( )' mean?

So I was having problems with a code before because I was getting an empty line when I iterated through the foodList.

Someone suggested using the 'if x.strip():' method as seen below.

for x in split:
  if x.strip():
    foodList = foodList + [x.split(",")]

It works fine but I would just like to know what it actually means. I know it deletes whitespace, but wouldn't the above if statement be saying if x had empty space then true. Which would be the opposite of what I wanted? Just would like to wrap my ahead around the terminology and what it is doing behind the scenes.

like image 875
Danrex Avatar asked Jun 23 '13 19:06

Danrex


2 Answers

In Python, "empty" objects --- empty list, empty dict, and, as in this case, empty string --- are considered false in a boolean context (like if). Any string that is not empty will be considered true. strip returns the string after stripping whitespace. If the string contains only whitespace, then strip() will strip everything away and return the empty string. So if strip() means "if the result of strip() is not an empty string" --- that is, if the string contains something besides whitespace.

like image 199
BrenBarn Avatar answered Sep 27 '22 19:09

BrenBarn


The method strip() returns a copy of the string in which all chars have been stripped from the beginning and the end of the string (default whitespace characters).

So, it trims whitespace from begining and end of a string if no input char is specified. At this point, it just controls whether string x is empty or not without considering spaces because an empty string is interpreted as false in python

like image 42
fatihk Avatar answered Sep 27 '22 18:09

fatihk