What does "if x.strip ()" mean?

So, I had problems with the code before, because I was getting an empty string when I repeated through foodList.

Someone suggested using the "if x.strip ():" method, as shown below.

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

This works great, but I just wanted to know what that really means. I know that it removes spaces, but the if statement above would not say if x had empty space, then true. What would be the opposite of what I wanted? Just wanted to get around my terminology and what it does behind the scenes.

+4
source share
2 answers

In Python, β€œempty” objects --- an empty list, an empty dict, and, as in this case, an empty string --- are considered false in a boolean context (for example, if ). Any string that is not empty will be considered true. strip returns a string after removing spaces. If the string contains only spaces, strip() will delete everything and return an empty string. Thus, if strip() means "if the result of strip() not an empty string" --- that is, if the string contains something other than spaces.

+8
source

The strip () method returns a copy of the string in which all characters were deleted from the beginning and end of the string (white space by default).

This way, it truncates spaces from the beginning and end of the line if char input is not specified. At the moment, it just controls whether the string x empty or not without spaces, because the empty string is interpreted as false in python

+2
source

Source: https://habr.com/ru/post/1487758/


All Articles