Learn Without Walls
← Previous Lesson Lesson 4 of 4 Practice Problems →

String Concatenation and Repetition

What You'll Learn

1. String Concatenation Revisited

Concatenation: Joining two or more strings end-to-end using the + operator to create a new string.

We introduced concatenation briefly in Module 2. Now let us explore it more deeply:

first = "Hello"
second = "World"

# Simple concatenation
result = first + second
print(result)

# With a space in between
result = first + " " + second
print(result)

# Building a longer string
greeting = first + " " + second + "!" + " How are you?"
print(greeting)
HelloWorld Hello World Hello World! How are you?
Remember: Concatenation does NOT add spaces automatically. You must include them yourself. Compare this with print() using commas, which adds spaces for you.

2. Concatenation Requires Strings

The + operator can only join strings with other strings. If you try to concatenate a string with a number, Python raises a TypeError:

name = "Alice"
age = 25

# This will cause a TypeError!
# message = "Age: " + age

# Solution 1: Convert with str()
message = "Age: " + str(age)
print(message)

# Solution 2: Use an f-string (usually better)
message = f"Age: {age}"
print(message)

# Solution 3: Use commas in print()
print("Age:", age)
Age: 25 Age: 25 Age: 25

3. String Repetition with *

The * operator repeats a string a specified number of times:

# Basic repetition
print("Ha" * 3)
print("- " * 10)
print("=" * 40)
HaHaHa - - - - - - - - - - ========================================

Repetition is especially useful for creating visual separators and borders:

Creating a Bordered Title

title = "MY REPORT"
width = 30

print("+" + "-" * (width - 2) + "+")
print("|" + title.center(width - 2) + "|")
print("+" + "-" * (width - 2) + "+")
+----------------------------+ | MY REPORT | +----------------------------+

Simple Text Art

print("  *")
print(" ***")
print("*****")
print("  |")
* *** ***** |

4. Building Strings with +=

The += operator appends text to an existing string:

message = "Hello"
message += ", "
message += "World"
message += "!"
print(message)
Hello, World!

Building a List of Items

shopping_list = "Shopping List:\n"
shopping_list += "- Apples\n"
shopping_list += "- Bread\n"
shopping_list += "- Milk\n"
shopping_list += "- Eggs"

print(shopping_list)
Shopping List: - Apples - Bread - Milk - Eggs

5. When to Use Which Approach

Python offers several ways to combine text and values. Here is when to use each:

f-strings -- Best for mixing variables and text. Use this as your default choice.
print(f"Hello, {name}! You are {age} years old.")
Commas in print() -- Best for quick debugging or when you just want to display values.
print("Name:", name, "Age:", age)
Concatenation (+) -- Best when building strings to store in variables, or joining a small number of strings.
full_name = first_name + " " + last_name
Repetition (*) -- Best for creating visual patterns or repeating content.
border = "=" * 40
Pro Tip: In most situations, f-strings are the cleanest and most readable option. Use them as your go-to choice. Save concatenation for when you need to build a string variable over multiple steps.

6. Practical Example: A Complete Program

# A program that combines everything from Module 3
name = input("Enter your name: ")
hours = float(input("Hours worked this week: "))
rate = float(input("Hourly rate: $"))

gross_pay = hours * rate
tax_rate = 0.15
taxes = gross_pay * tax_rate
net_pay = gross_pay - taxes

# Formatted output using multiple techniques
border = "=" * 35
print()
print(border)
print(f"  Pay Stub for {name}")
print(border)
print(f"  Hours Worked:  {hours}")
print(f"  Hourly Rate:   ${rate:.2f}")
print(f"  Gross Pay:     ${gross_pay:,.2f}")
print(f"  Taxes ({tax_rate:.0%}):   ${taxes:,.2f}")
print("-" * 35)
print(f"  Net Pay:       ${net_pay:,.2f}")
print(border)

Check Your Understanding

Question 1: What is the output of "abc" + "def"?

Answer: "abcdef" -- concatenation joins strings with no space.

Question 2: What is the output of "Ha" * 4?

Answer: "HaHaHaHa"

Question 3: When should you use f-strings instead of concatenation?

Answer: Use f-strings when mixing variables and text. They are more readable and do not require str() conversion. Use concatenation for simple string joining or building strings incrementally with +=.

Try It Yourself!

  1. Build a full name from first, middle, and last name variables using concatenation.
  2. Create a decorative border using * repetition around a message.
  3. Write a program that asks for a user's name and creates a personalized greeting card using borders and f-strings.

Key Takeaways

← Previous: f-strings Practice Problems →