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

~90s

Three slices of one string

What does this Python program print?

s = "PLACEMENT"
print(s[2:6], s[::-1][:3], s[-3:])
Show the answer and the worked solution

Correct answer: C.

ACEM TNE ENT

Worked solution

  1. 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.
  2. s[::-1] is TNEMECALP, and taking its first three characters gives TNE.
  3. 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.

Three slices of one string — Aptitude Question

Three slices of one string: What does this Python program print? Answer and worked solution on CodeKairo.

Question

What does this Python program print?

s = "PLACEMENT"
print(s[2:6], s[::-1][:3], s[-3:])

Options

  1. ACE TNE ENT
  2. ACEM ENT TNE
  3. ACEM TNE ENT
  4. LACE TNE ENT
Show the answer and the worked solution

Correct answer: C. ACEM TNE ENT

Worked solution

  1. 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.
  2. s[::-1] is TNEMECALP, and taking its first three characters gives TNE.
  3. 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