Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Duplicate String N Times

Repeat a string n times with multiplication. Students distinguish numeric multiplication from text repetition and test zero or negative repeat counts honestly.

BeginnerPhase 5 - Category 4: String TransformationExample 7 of 10
duplicate-string-n-times.py
1# Take string input
2s = input("Enter a string: ")
3n = int(input("Enter number of times: "))
4
5# Duplicate
6result = s * n
7print(result)

Output

Enter a string: Hello
Enter number of times: 3
HelloHelloHello

In this one

  • Repeat text with multiplication
  • Handle nonpositive counts
  • Recognize allocation costs

How it works

  1. 1

    Read s and convert the repeat count.

  2. 2

    Calculate s * n.

  3. 3

    Print the complete repeated result.

Edge cases

Does a negative n raise an error here?

Does a negative n raise an error here?

No. String repetition returns empty text.

Are spaces inserted between copies?

Are spaces inserted between copies?

No. Only characters already in s are repeated.

What's going on

s * n concatenates n copies of the string when n is positive. It adds no separator between them.

For ab repeated three times, the result is ababab. A zero or negative count returns empty text rather than raising an error. The final print still adds a newline. Large repeat counts can allocate substantial memory because the complete result is created.

Does a negative n raise an error here? No. String repetition returns empty text.

Are spaces inserted between copies? No. Only characters already in s are repeated.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What is ab * 2 conceptually?

Pick an answer to check it.

Question 2

Does a negative n raise an error here?

Pick an answer to check it.

Questions people ask

Does a negative n raise an error here?

No. String repetition returns empty text.

Are spaces inserted between copies?

No. Only characters already in s are repeated.

What is ab * 2 conceptually?

abab.