Skip to main content

How to Repeat a String in Python with *

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

To print a line of dashes under a heading, or to build a long test text from one sentence, you need the same text several times. In Python, * between a string and a whole number repeats the string that many times. This guide repeats three strings on Python 3.15.2.

Syntax​

Syntax
<text> * <times>
PartWhat it means
<text>The string to repeat
<times>A whole number: how many copies of the text the result holds. <times> * <text> works too

Strings are sequences in Python, and the documentation on sequence operations describes s * n or n * s as "equivalent to adding s to itself n times". The result is a new string.

The Example​

A laugh repeated three times, a dash repeated twenty times to draw a line, and a word with a space after it, repeated three times.

Prerequisites​

  • uv and Python 3. This guide uses uv 0.13.10 with Python 3.15.2, in a project made with uv init.

Step 1: Write the Script​

repeat.py
print("ha" * 3)
print("-" * 20)

word = "echo "
print(word * 3)

The repeat.py script in a macOS-style code window: prints of ha times 3 and of a dash times 20, then the word echo followed by a space, stored in word and printed times 3.

Step 2: Run It​

Terminal
uv run python repeat.py
Output
hahaha
--------------------
echo echo echo

The terminal after uv run python repeat.py: hahaha, a line of twenty dashes, and echo echo echo.

  • "ha" * 3 joined three copies with nothing between them: hahaha.
  • "-" * 20 drew a line of twenty dashes.
  • "echo " * 3 kept the space at the end of each copy, so the words came out apart. The last copy's space is there too, at the end of the line, where you can't see it.

The command works unchanged in PowerShell.

Common Mistakes​

MistakeWhat happensDo this instead
Repeating by a decimal number, "ha" * 2.5TypeError: can't multiply sequence by non-int of type 'float'Use a whole number
Repeating by a number written as text, "ha" * "3"TypeError: can't multiply sequence by non-int of type 'str'Multiply by the number itself: "ha" * 3
Expecting a space between the copies"ha" * 3 gives hahaha, with no spacesPut the space in the text, as "echo " does, or join a repeated list with " ".join(...)

FAQ​

Does the order matter, text first or number first?​

No. 3 * "ha" printed hahaha, the same as "ha" * 3.

What happens with 0 or a negative number?​

You get an empty string: "ha" * 0 and "ha" * -1 both gave ''.

Conclusion​

"ha" * 3 gave hahaha, "-" * 20 a line of twenty dashes, and "echo " * 3 three words with spaces: * repeated each string in a new string.

Additional Resources​