โ† Back

Home โ€บ Problems โ€บ String multiplication and indexing

String multiplication and indexing

๐Ÿง  Predict the output Topic: strings Difficulty: easy Free

What this problem practises

Python strings are immutable sequences. "Fixing" a string always produces a new one, so the return value has to be captured; slicing rules apply, and every method โ€” upper(), strip(), split(), join() โ€” behaves differently from the in-place mutation you might be picturing.

This is an output-prediction problem: read the snippet carefully and write down exactly what it prints before anything runs. These questions are interview staples because they test whether you know the language rules, or merely recognise their syntax.

Difficulty: easy โ€” the fix or the trick is normally a single line, and a careful read should be enough.

The challenge

The code runs in PyDebugโ€™s in-browser compiler. Open the problem, run the snippet, watch the exact error or output, and keep iterating until it is right. Signed-in solves count toward XP and your daily streak.

The snippet

The interactive editor pre-fills exactly this code โ€” read it, then submit your prediction:

s = "ab" * 2
print(s)
print(s[0])
print(s[-1])

Understand the rule

This puzzle layers two string rules: multiplication builds a longer repeated string, and indexing then reads one character of the RESULT โ€” not of the original. ('ab' * 3)[4] first constructs 'ababab', then takes position 4, which is 'a'. Doing the operations in the written order, one at a time, is the entire technique.

How to trace it

  1. Resolve the multiplication completely: write out the full repeated string.
  2. Number the characters of the result from 0.
  3. Apply the index (or slice) to that numbered string, translating negatives from the end.
  4. Only then apply any further operation like len() or another concatenation.

Common wrong fixes

Rule to remember

Evaluate in order: build the repeated string first, then index the result. Writing the intermediate string down turns a trick question into a lookup.

Solve it in the interactive editor โ†’

๐Ÿ”ฎ Learning path: Output Prediction

Problem 2 of 18 in this path. Work them in order โ€” each one builds on the rule before it.

โ† String repetition and lengthNext in path: String multiplication in a loop โ†’

๐Ÿ’ผ Learning path: Interview Practice

Problem 16 of 16 in this path. Work them in order โ€” each one builds on the rule before it.

โ† try-except-else flow๐Ÿ Path complete โ€” review it โ†’

More strings problems

Keep going