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.

cweiske
  • 30,033
  • 14
  • 133
  • 194
Mir
  • 670
  • 4
  • 9
  • 20
  • 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. – cdarke Mar 05 '12 at 11:30
  • @cdarke Yes I did. I had one of those 'blonde' (no offense to blondes) moments. :D – Mir Mar 05 '12 at 19:33
  • Duplicate of [Why doesn't calling a Python string method do anything unless you assign its output?](https://stackoverflow.com/questions/9189172/why-doesnt-calling-a-python-string-method-do-anything-unless-you-assign-its-out) – smci Aug 23 '18 at 06:54

2 Answers2

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)
Bogdan
  • 8,017
  • 6
  • 48
  • 64
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()
Community
  • 1
  • 1
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561