Strip() question

Why is it that when I use column.strip() to strip the column name of whitespace, I have to save this in another variable? I was reading the documentation and it looked like the function acts on the calling string. How do I know when I need to save the result to a variable? Do all string operations need to be saved to a new variable?

Thanks for letting me practice asking questions!

Whether you need to save to another depends on 2 issues.

  1. Whether the object is mutable
  2. Whether the designer of the function processed the object in-place returning the same object, or returned a new object.

For this particular question, I assume column is of str type. Strings are immutable. You can’t edit them in place, so any processing will create a new string in memory (except interned strings: String Interning in Python (Optimization)) , and you have to assign the new string to a variable, so you can later use that variable to reference the new string.

Yes.

For mutable objects like lists, then the designer has a choice. For example ,list.sort vs sorted(list). First one sorts in place and returns None. Second one returns the sorted list.

If you’re using pandas, although you can do inplace=True, here’s a list of reasons why you should not: Why You Should Probably Never Use pandas inplace=True | by Sven Harris | Aug, 2021 | Towards Data Science

1 Like