Home โบ Problems โบ String repetition and length
String repetition and length
๐ง 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:
word = "code"
print(word * 3)
print(len(word))Understand the rule
'ab' * 3 builds 'ababab' โ string multiplication repeats the whole string, not each character, and len() then counts every character of the result. Predicting these snippets is pure arithmetic once the rule is stated: len(s * n) equals len(s) * n. The traps are the edge cases: multiplying by zero or a negative number yields the empty string.
How to trace it
- Expand the repetition literally: write out s repeated n times before doing anything else.
- Apply len() to the expanded result, counting every character including spaces.
- Check operator order: 'ab' * 2 + 'c' differs from 'ab' * (2 + 1) โ multiplication binds tighter than addition.
- Handle edge multipliers: s * 0 and s * -1 are both '', with length 0.
Common wrong fixes
- Multiplying the length of the string mentally but forgetting a space or punctuation inside it.
- Expecting 'ab' * 3 to interleave ('aabbab' style guesses) instead of repeating the block.
- Assuming s * 2.0 works; string repetition requires an integer and raises TypeError for floats.
Rule to remember
s * n concatenates n full copies of s, so len(s * n) = len(s) * n, and any n โค 0 produces the empty string. Expand first, count second.
๐ฎ Learning path: Output Prediction
Problem 1 of 18 in this path. Work them in order โ each one builds on the rule before it.
โฉ Path overviewNext in path: String multiplication and indexing โ
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.