Three slices of one string — Aptitude Question
Three slices of one string: What does this Python program print? Answer and worked solution on CodeKairo.
- Topic: Programming Fundamentals
- Section: Programming MCQs
- Difficulty: Medium
- Time target: 90 seconds
Question
What does this Python program print?
s = "PLACEMENT"
print(s[2:6], s[::-1][:3], s[-3:])Options
- ACE TNE ENT
- ACEM ENT TNE
- ACEM TNE ENT
- LACE TNE ENT
Show the answer and the worked solution
Correct answer: C. ACEM TNE ENT
Worked solution
- The letters sit at indices 0 to 8: P L A C E M E N T. s[2:6] takes indices 2, 3, 4 and 5, which is ACEM.
- s[::-1] is TNEMECALP, and taking its first three characters gives TNE.
- s[-3:] counts back three from the end and runs to the end, giving ENT, so the line prints ACEM TNE ENT.
Answer: ACEM TNE ENT.
The idea
A slice s[i:j] contains j − i characters when both bounds are in range, which makes the length a quick sanity check. Chained slices are applied left to right, each one working on the result of the last.
Shortcut. s[2:6] has 6 − 2 = 4 letters starting at index 2 (A), which rules out ACE and LACE; the reversed slice reads backwards (TNE) and the last three forwards (ENT).
Common trap. "LACE TNE ENT" counts positions from 1, so it starts at L; Python indexes from 0, so index 2 is A.
All Programming Fundamentals questions · placement mock tests