← Back to Python, page 5

python-0081 · Easy fresher

Why does calling s.strip() leave s unchanged? Predict the output of this string-cleaning code.

String methods never change the original string; they return a new one. Calling s.upper() or s.replace() without assigning the result has no effect on s. Building a string by repeated += creates new strings each time, so join is preferred in loops.

Full answer
python
s = "  Hello World  "
s.strip()
s.upper()
print(repr(s))
t = s.strip().replace("World", "Python").upper()
print(repr(t), repr(s))
try:
    t[0] = "J"
except TypeError as e:
    print("TypeError:", e)
parts = ["a", "b", "c"]
print("-".join(parts), "J" + t[1:])

Output:

text
'  Hello World  '
'HELLO PYTHON' '  Hello World  '
TypeError: 'str' object does not support item assignment
a-b-c JELLO PYTHON

The first two method calls compute new strings and throw them away, so s still has its spaces and original case. Chaining methods and assigning the result to t gives the cleaned value while s remains unchanged. Item assignment on a string raises a TypeError because strings cannot be modified in place; slicing and concatenation build a new string instead. join combines many parts in one step.

python
s = "  Hello World  "
s.strip()
s.upper()
print(repr(s))
t = s.strip().replace("World", "Python").upper()
print(repr(t), repr(s))
try:
    t[0] = "J"
except TypeError as e:
    print("TypeError:", e)
parts = ["a", "b", "c"]
print("-".join(parts), "J" + t[1:])

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • String methods return new strings
  • Assign the result to keep it
  • Item assignment raises TypeError
  • Chain methods for cleanup
  • join for combining many parts

Common mistakes

  • Calling s.strip() and expecting s to change
  • Concatenating in a loop with +=

Follow-ups

  • Why are strings immutable?
  • How does io.StringIO help when building text?

Tips

  • Point out the discarded results