0

I found it odd that a string method operation on a string object doesn't modify the string object. Why is it? I wasted quite a bit of time yesterday trying to understand why my code wasn't working when I finally discovered this.

3
  • 1
    Maybe ask yourself why you thought strings could be modified. Did the documentation mis-lead you? Did you make an assumption because some other language works in a different way? By the way, numbers are also immutable. Commented Mar 5, 2012 at 11:30
  • @cdarke Yes I did. I had one of those 'blonde' (no offense to blondes) moments. :D Commented Mar 5, 2012 at 19:33
  • Duplicate of Why doesn't calling a Python string method do anything unless you assign its output? Commented Aug 23, 2018 at 6:54

2 Answers 2

4

Strings are immutable types in python. Main advantages of being immutable would be:

  • simplify multithreaded programming.
  • can be used as dictionary keys (will keep the same hash)
Sign up to request clarification or add additional context in comments.

Comments

4

Strings are immutable by design in Python. This is common to many other languages, too, so it's not a Python-specific thing. For the "Why?" please see these excellent answers here on SO, and also this great blog post by Eric Lippert.

That's why string operations always return a new string (which you then may re-assign to the same name as before like

mystr = mystr.upper()

3 Comments

And you can use mystr.strip().lower()
@warwaruk: True, but you could do that also if the method would modify the string in-place (and also return it). Of course, that would violate another Python principle...
@warwaruk: That's what I meant by "violating another principle".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.