Why do I need to nest methods in a single line when using .strip?

In the exercise: String Methods: .Strip( )

This does not work:

love_maybe_lines_stripped =
for line in love_maybe_lines:
line.strip()
love_maybe_lines_stripped.append(line)

But this does:

love_maybe_lines_stripped =
for line in love_maybe_lines:
love_maybe_lines_stripped.append(line.strip())

The only difference (bold) is that the line.strip() is nested in a single compound line with the .append() method in the working code. Why do the methods need to be nested in a single line? Does the computer “forget” the line has been stripped of spaces if you break up the .strip and .append into two separate lines in the same loop? Makes no sense to me.

Hey there and welcome to the forums :slight_smile:

Some methods, such as .strip() don’t actually modify the variable they are being used on. Instead they return a modified copy of it. So when you did line.strip() you didn’t modify line, just called a function that returned a stripped copy of it. Since you did not assign this value goes no were and is lost.
By nesting it in .append() (which is a method that does modify the value it was called on) you return the modified string as an argument to .append().

Another way you can modify a string with .strip() is:

string = "  hello  "
string = string.strip() 

Over time you get to learn what methods modify and which return a modified copy, though if your ever in doubt, a quick Google search or a look at the documentation usually helps.

1 Like

Thank you 8-bit-gaming,

I figured it was something like that. Because I didn’t assign the output of line.strip( ) to a variable (container), it was lost before being used in the following line. As a beginner, I assumed the output from line.strip( ) would be transiently saved in memory somewhere until the loop completed. Clearly I was wrong.
Thank you for your help. I really appreciate it… especially how quickly you responded!

2 Likes