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.
-
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– cdarke2012-03-05 11:30:56 +00:00Commented Mar 5, 2012 at 11:30
-
@cdarke Yes I did. I had one of those 'blonde' (no offense to blondes) moments. :DMir– Mir2012-03-05 19:33:25 +00:00Commented Mar 5, 2012 at 19:33
-
Duplicate of Why doesn't calling a Python string method do anything unless you assign its output?smci– smci2018-08-23 06:54:35 +00:00Commented Aug 23, 2018 at 6:54
Add a comment
|
2 Answers
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
warvariuc
And you can use
mystr.strip().lower()Tim Pietzcker
@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
@warwaruk: That's what I meant by "violating another principle".