String Concatenation and Repetition
What You'll Learn
- Building strings with the
+(concatenation) operator - Repeating strings with the
*operator - When to use concatenation vs. f-strings vs. commas in print()
- The
+=operator for building strings incrementally - Practical string-building patterns
1. String Concatenation Revisited
+ 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)
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)
3. String Repetition with *
The * operator repeats a string a specified number of times:
# Basic repetition print("Ha" * 3) print("- " * 10) print("=" * 40)
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) + "+")
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)
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)
5. When to Use Which Approach
Python offers several ways to combine text and values. Here is when to use each:
print(f"Hello, {name}! You are {age} years old.")
print("Name:", name, "Age:", age)
full_name = first_name + " " + last_name
border = "=" * 40
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!
- Build a full name from first, middle, and last name variables using concatenation.
- Create a decorative border using
*repetition around a message. - Write a program that asks for a user's name and creates a personalized greeting card using borders and f-strings.
Key Takeaways
+concatenates strings (no automatic spaces).*repeats a string a given number of times.- Concatenation requires all parts to be strings -- use
str()to convert numbers. +=appends text to an existing string variable.- f-strings are usually the best choice for mixing text and variables.
- Use commas in print() for quick output with automatic spaces.
- Use concatenation when building strings to store in variables.
- Use repetition for visual patterns and separators.