Skip to content

String immutability: method returns new string

Quick summary

You called s.upper() or s.replace() without assigning the result — strings are immutable, so the original is unchanged.

Why this happens

  • You called a string method without assigning the return value, expecting the original string to be modified in-place

  • You chained methods but forgot that each returns a new string and the intermediate results are discarded

  • You assumed strings are mutable like lists, but string methods always return a new string object

Minimal example

✗ Broken code
s = 'hello'
s.upper()  # result discarded!
print(s)  # 'hello' — unchanged
✓ Fixed code
s = 'hello'
s = s.upper()  # assign the result
print(s)  # 'HELLO'

Strings are immutable in Python, so upper() returns a new string — assigning it back to s replaces the reference with the uppercase version.

How to diagnose

  • Print the string before and after the method call to confirm it did not change

  • Check if the method call result is captured in a variable or discarded as a bare expression

  • Use id() to verify that the string object identity changes after the method call

How to fix

  • Assign the result of the string method back to the variable: s = s.upper() or s = s.replace('a', 'b')

  • Chain methods with assignment: s = s.strip().lower().replace('old', 'new')

  • Use a list of characters if you need in-place mutation, then join() back to a string when done

How to prevent

  • Remember that Python strings are immutable — always assign method results to a variable

  • Use a linter that warns about discarded expression results (bare string method calls)

Related Resources

Related Glossary

Related Lessons

← Back to language