Skip to content

Module 7 · Strings — topic 6 of 22

Repetition

Repeat a string with the * operator. Learn the rules for the repeat count, practical uses for separators, padding and simple patterns, and how repetition combines with other operations.

Beginner 8 min read·Lesson 87 of 306 in Python Programming

Learning objectives

  • Repeat strings with *
  • Use repetition for separators and simple text art
  • Combine repetition with concatenation and len()

Definition

Repeat a string with the * operator. Learn the rules for the repeat count, practical uses for separators, padding and simple patterns, and how repetition combines with other operations.

Introduction

Multiplying a string by an integer repeats it. "-" * 10 produces ten dashes, and "ab" * 3 produces "ababab". It is a small feature that makes text output much neater.

Why it matters

Underlines, borders, progress bars, indentation and simple patterns are all repeated characters. Repetition creates them in one expression and can adapt the length to the data, such as an underline as long as a title.

Detailed explanation

Repetition is evaluated before concatenation because * has higher precedence than +, so "=" * 3 + "|" is "===|". Add parentheses when you want to repeat a combined piece: ("ab" + "-") * 2 gives "ab-ab-".

Repetition is also a quick way to create test data, for example a string of 10,000 characters to check how a function copes with very long input.

s * n and n * s both repeat s n times.

n must be an integer. A float such as 2.0 raises TypeError, even if it is whole.

n = 0 or any negative n produces the empty string.

Repetition creates a new string; the original is unchanged.

Combine with len() to match the width of other text: "=" * len(title).

Combine with concatenation for padding: " " * (width - len(text)) + text right-aligns text, although the string method rjust() or format specifiers do this more cleanly.

The same operator repeats lists and tuples.

Syntax

Python
line = "-" * width
underline = "=" * len(title)
  • The count must be an integer.
  • Zero or negative counts give "".
  • Use len() to match other text.

Code examples

Basic repetition

Python
print("-" * 12)
print("ab" * 3)
print(repr("x" * 0), repr("x" * -2))
Output
------------
ababab
'' ''

Underlining a title

Python
title = "Monthly Report"
print(title)
print("=" * len(title))
Output
Monthly Report
==============

More examples

A text bar chart

Python
sales = {"Mon": 12, "Tue": 7, "Wed": 15, "Thu": 4}
longest = max(len(day) for day in sales)
for day, count in sales.items():
print(day + " " * (longest - len(day)), "|", "#" * count, count)
print("-" * 24)
for level in range(1, 4):
print(" " * (3 - level) + "*" * (2 * level - 1))
Output
Mon | ############ 12
Tue | ####### 7
Wed | ############### 15
Thu | #### 4
------------------------
  *
 ***
*****

Step-by-step explanation

  • longest is the length of the longest day name, used for alignment.
  • " " * (longest - len(day)) pads shorter names (all are 3 letters here, so no padding is added).
  • "#" * count draws a bar whose length equals the value.
  • The final loop combines leading spaces and stars to draw a small triangle.

Expected output

Running “A text bar chart” prints exactly:

TextOutput
Mon | ############ 12
Tue | ####### 7
Wed | ############### 15
Thu | #### 4
------------------------
*
***
*****

Practical applications

  • Command-line tools print progress bars with repeated characters.
  • Report generators draw separators and boxes around tables.
  • Code generators indent lines with " " * (4 * depth).

Best practices

  • Use repetition for separators and visual bars.
  • Use // when computing repeat counts.
  • Use str methods such as center() and ljust() for alignment.

Common mistakes

Repeating with a float

Avoid

"=" * (width / 2)

Prefer

"=" * (width // 2)

/ produces a float, which can’t be a repeat count.

Expecting repetition to add separators

Avoid

"apple" * 2 # expecting "apple apple"

Prefer

" ".join(["apple"] * 2)

Repetition joins copies with nothing in between.

Key takeaways

  • s * n repeats s n times; n must be an int.
  • Zero or negative n gives the empty string.
  • Combine with len() to size separators to text.

Try it yourself

  1. 1
    Print a 5-line box made of # characters, 10 wide, with spaces inside.
  2. 2
    Draw a bar chart of three test scores divided by 10 using repeated characters.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

17 questions cover the “Strings” module. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
  • BeginnerWhat is printed?
  • BeginnerWhat is printed?
Practise this module