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
- Resolve the multiplication completely: write out the full repeated string.
- Number the characters of the result from 0.
- Apply the index (or slice) to that numbered string, translating negatives from the end.
- Only then apply any further operation like len() or another concatenation.
Common wrong fixes
- Indexing the original short string and then imagining the repetition afterwards.
- Losing count because the repeated string's pattern makes positions blur โ write it out, don't eyeball it.
- Ignoring operator precedence: 'ab' * 3[0] is a TypeError (3[0] first), unlike ('ab' * 3)[0].
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.
๐ฎ 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
- Output-prediction strategies โ how to predict tricky snippets without running them.
- Browse every strings problem in this topic.
- Common Python errors and what they actually mean, plus the Python glossary for any term used on this page.