Hey so im confused on how to use the .strip() method I looked it up on w3school I cant think of what I’m doing wrong it should be removing the white space before and after but for whatever reason its not can I get an explanation on what I’m doing wrong?
It’s because this method does not modify the string itself (the string is immutable) but creates a new string object. You’d need to assign a name to this new string with assignment or make use of it as-is. You can check the docs for
.strip() if you want more details-
I dont understand im doing it just like the example every index is assigned as “I” similar to how the example is just that its one string alone and that .strip works
@tgrtim is correct.
strip() does not modify the string in-place (like
list.sort()) as strings are immutable. When you say it works individually you are directly printing the result of stripping the string:
print(featuring.strip()) #here, you print and strip in the same line-which will print the stripped string
In your loop, however you simply have a line
i.strip() which returns a stripped value, yet there is nothing to hold it.
got it I see what your saying I had to hold it in a variable it still doesn’t make sense to me though as the variable and what is assigned to it is the same thing to my understanding
If you check the original link you’ll see that the description for
.strip() states that it “Return a copy of the string…”. Importantly that means that the string itself is unchanged. Try the following if you prefer the visual output-
print(i) # original string is printed print(i.strip()) # returns a copy that gets printed print(i) # original string has not changed when printed again despite .strip being called
for the change. This is how most string methods work (those that return strings) because the string type itself is immutable and cannot be changed. So what you get instead is a copy with the relevant alterations/additions.