AI InterviewSearch…Search problems, topics, or pages…Ctrl KGet started
Easypythonstringsimmutability

~60s

Python strings are immutable too

What does this Python program print?

s = "python"
s.upper()
s.replace("p", "P")
print(s)
Show the answer and the worked solution

Correct answer: A.

python

Worked solution

  1. upper and replace both return new strings and leave the original untouched, because str is immutable.
  2. Neither returned value is assigned, so both are discarded straight away.
  3. s still refers to the original object and python is printed.

Answer: python.

The idea

String methods in Python are pure functions dressed as methods. Only s = s.upper() changes what the name refers to, and even then the original object is unchanged.

Shortcut. No line begins s =, so s cannot come to refer to anything new, and a str cannot change in place: it prints python.

Common trap. "PYTHON" assumes both methods change s in place; upper() would then give PYTHON, and the replace would find no lowercase p to change.

Python strings are immutable too — Aptitude Question

Python strings are immutable too: What does this Python program print? Answer and worked solution on CodeKairo.

Question

What does this Python program print?

s = "python"
s.upper()
s.replace("p", "P")
print(s)

Options

  1. python
  2. Python
  3. PYTHON
  4. The program raises an AttributeError
Show the answer and the worked solution

Correct answer: A. python

Worked solution

  1. upper and replace both return new strings and leave the original untouched, because str is immutable.
  2. Neither returned value is assigned, so both are discarded straight away.
  3. s still refers to the original object and python is printed.

Answer: python.

The idea

String methods in Python are pure functions dressed as methods. Only s = s.upper() changes what the name refers to, and even then the original object is unchanged.

Shortcut. No line begins s =, so s cannot come to refer to anything new, and a str cannot change in place: it prints python.

Common trap. "PYTHON" assumes both methods change s in place; upper() would then give PYTHON, and the replace would find no lowercase p to change.

All Programming Fundamentals questions · placement mock tests