Remove Whitespace (Solution)
00:00 So the task is to remove the whitespace, clean the menu.
00:09 And I’ve copied the three strings like mentioned before, so I cannot do this.
00:16 Okay, so the issue with IDLE’s interpreter is that you can’t paste multiple lines. I think it’s confused by that. So you can’t actually do what I suggested you to do in this specific REPL.
00:25 You can do it in some alternative REPLs. The first one might have gotten defined, but I can just copy them separately one line at a time, and then it’ll work.
00:38
Now I have access to all three of those, string1
, string2
, and string3
—oops, 4
, I do not have that. Here it is.
00:48 And you can see that they have this whitespace that you should get rid of.
00:53
Now, the string method to do this is .strip()
. So you can say, for example, string3.strip()
and that’ll remove the whitespace both at the beginning as well as at the end, which means that you could use .strip()
for each of those strings, and it’ll do what you’re asked to do.
01:14 But Python also has two more specific methods here where you can just remove space from the right side or from the left side, which I will apply for the ones over here.
01:24
So for string1
, I can say .lstrip()
, which is going to strip away whitespace from the left side but not do anything on the right side.
01:32
And string2
I can use .rstrip()
, which does the opposite. It just removes from the right side but not from the left. And to show you the difference, so if I would use any of those on string3
, so for example, .lstrip()
on string3
is going to remove the whitespace on the left, but it’s going to leave it on the right. And the opposite, if I say string3.rstrip()
, then you can see that the whitespace on the left stays, but the one on the right gets removed.
02:07
You can either use .strip()
for all of them, and that’ll work, or you can use the more specific .lstrip()
and .rstrip()
for string1
or string2
, respectively.
02:18
And we’ve also learned that you cannot paste multiple lines in one go into the Python interpreter. That’s going to cause a SyntaxError
where Python just tells you, no, this doesn’t work, but you can paste one line at a time.
Become a Member to join the conversation.