โ† Back

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

  1. Expand the repetition literally: write out s repeated n times before doing anything else.
  2. Apply len() to the expanded result, counting every character including spaces.
  3. Check operator order: 'ab' * 2 + 'c' differs from 'ab' * (2 + 1) โ€” multiplication binds tighter than addition.
  4. Handle edge multipliers: s * 0 and s * -1 are both '', with length 0.

Common wrong fixes

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.

Solve it in the interactive editor โ†’

๐Ÿ”ฎ 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