0
0
PythonHow-ToBeginner · 3 min read

How to Repeat a String in Python: Simple Syntax and Examples

In Python, you can repeat a string by using the * operator followed by the number of times you want to repeat it. For example, 'hello' * 3 produces 'hellohellohello'. This is a simple and efficient way to duplicate strings.
📐

Syntax

The syntax to repeat a string in Python uses the * operator between a string and an integer. The integer specifies how many times the string should be repeated.

  • string * n: repeats string n times.
  • string: any text enclosed in quotes.
  • n: a non-negative integer.
python
repeated_string = 'abc' * 4
print(repeated_string)
Output
abcabcabcabc
💻

Example

This example shows how to repeat the word hello three times and print the result.

python
word = 'hello'
repeated = word * 3
print(repeated)
Output
hellohellohello
⚠️

Common Pitfalls

Common mistakes include:

  • Using a non-integer or negative number to repeat the string, which causes errors or empty results.
  • Trying to repeat a string without the * operator.

Always ensure the number is a non-negative integer.

python
wrong = 'test' * -1  # This results in an empty string
print(wrong)

# Correct way:
correct = 'test' * 2
print(correct)
Output
testtest
📊

Quick Reference

OperationDescriptionExampleResult
Repeat stringMultiply string by integer'abc' * 3'abcabcabc'
Repeat zero timesMultiply string by zero'abc' * 0'' (empty string)
Negative repeatMultiply string by negative number'abc' * -1'' (empty string)

Key Takeaways

Use the * operator to repeat a string by an integer number of times.
The number must be a non-negative integer; negative or non-integers give empty strings or errors.
Repeating a string zero times returns an empty string.
This method is simple, fast, and built into Python.
Avoid forgetting the * operator or using invalid repeat counts.