Python strings are immutable too — Aptitude Question
Python strings are immutable too: What does this Python program print? Answer and worked solution on CodeKairo.
- Topic: Programming Fundamentals
- Section: Programming MCQs
- Difficulty: Easy
- Time target: 60 seconds
Question
What does this Python program print?
s = "python"
s.upper()
s.replace("p", "P")
print(s)Options
- python
- Python
- PYTHON
- The program raises an AttributeError
Show the answer and the worked solution
Correct answer: A. python
Worked solution
- upper and replace both return new strings and leave the original untouched, because str is immutable.
- Neither returned value is assigned, so both are discarded straight away.
- 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