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.
Asked
Active
Viewed 160 times
0
-
1Maybe 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 Answers
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
-
-
@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... – Tim Pietzcker Mar 05 '12 at 10:37
-
@warwaruk: That's what I meant by "violating another principle". – Tim Pietzcker Mar 05 '12 at 11:38