String Concatenation and Formatting

What is String Concatenation?

String concatenation means combining multiple strings together to create one longer string. It’s like gluing words together to make sentences.

Simple example:

first_name = "Alice"
last_name = "Smith"
full_name = first_name + " " + last_name  # "Alice Smith"

There are several ways to combine strings in Python, each with its own advantages and use cases.


Method 1: The + Operator (String Addition)

How it works: Use the + symbol to “add” strings together.

# Basic concatenation
greeting = "Hello" + " " + "World"
print(greeting)  # Output: Hello World

# With variables
first_name = "Bob"
message = "Welcome, " + first_name + "!"
print(message)  # Output: Welcome, Bob!

# Multiple concatenations
app_name = "Flashcard"
version = "1.0"
title = app_name + " App " + "v" + version
print(title)  # Output: Flashcard App v1.0

Points to note

  • You need to explicitly add spaces, e.g.:
    message = "I am " + name + " and my first language is " + first_language"
    
  • You can only use + to concatenate strings when everything you want to concatenate is a string. For example, this will not work because version is a float:
    app_name = "Flashcard"
    version = 1.0
    title = app_name + " App " + "v" + version # Output: TypeError: can only concatenate str (not "float") to str
    

Limitations:

  • Can get messy with many variables
  • Must convert numbers to strings first
  • Hard to read with complex combinations

❌ Common Mistake:

name = "Alice"
age = 25

# This will cause an error!
message = "I am " + name + " and I am " + age + " years old"
# TypeError: can only concatenate str (not "int") to str

# Fix by converting numbers to strings:
message = "I am " + name + " and I am " + str(age) + " years old"


← Back to where you were | → Start the course from the beginning


Method 2: The , separator in print()

How it works: Use commas in print() to display multiple values with automatic spacing.

# Basic usage
print("Hello", "World")  # Output: Hello World

# With variables
name = "Charlie"
age = 30
print("My name is", name, "and I am", age, "years old")
# Output: My name is Charlie and I am 30 years old

# Multiple types automatically handled
score = 95
total = 100
print("You scored", score, "out of", total, "points!")
# Output: You scored 95 out of 100 points!

Points to note

  • Automatically handles different data types (no str() needed)
  • Adds spaces between items automatically

Limitations:

  • Only works with print() - can’t save result to a variable
  • Always adds spaces (can’t control spacing precisely)
  • Limited formatting options

Customizing the separator:

# Change the separator
print("apple", "banana", "cherry", sep=", ")
# Output: apple, banana, cherry

print("2024", "12", "25", sep="-")
# Output: 2024-12-25

# Remove separator entirely
print("Hello", "World", sep="")
# Output: HelloWorld


← Back to where you were | → Start the course from the beginning


Method 3: F-Strings (Formatted String Literals)

How it works: Put an f before your string and use {} as placeholders for variables.

# Basic f-string
name = "Diana"
message = f"Hello, {name}!"
print(message)  # Output: Hello, Diana!

# Multiple variables
first_name = "John"
last_name = "Doe"
age = 28
introduction = f"My name is {first_name} {last_name} and I am {age} years old."
print(introduction)
# Output: My name is John Doe and I am 28 years old.

Advanced F-String Features:

1. Expressions inside braces:

length = 10
width = 5
print(f"The area is {length * width} square units")
# Output: The area is 50 square units

score = 85
total = 100
print(f"You got {score/total*100}% correct!")
# Output: You got 85.0% correct!

2. Number formatting:

Decimal places

E.g.

price = 19.99
print(f"The price is ${price:.2f}")  # 2 decimal places
# Output: The price is $19.99
  • {price:.2f} formats price to 2 decimal places
  • The f means “float” (decimal number)
Percentages

E.g.

score = 0.875
print(f"Success rate: {score:.1%}")  # As percentage
# Output: Success rate: 87.5%
  • {score:.1%} formats score to a percentage with one decimal place
  • the % symbol means percentage
Separators in large numbers

E.g.

population = 1234567
print(f"Population: {population:,}")  # Add commas
# Output: Population: 1,234,567
  • {population:,} formats population to a comma-split number
  • the , symbol indicates that it should be displayed with the comma-splits

3. Method calls and complex expressions:

name = "alice"
print(f"Hello, {name.title()}!")  # Capitalize first letter
# Output: Hello, Alice!

items = ["apple", "banana", "cherry"]
print(f"We have {len(items)} items: {', '.join(items)}")
# Output: We have 3 items: apple, banana, cherry

Points to note:

  • Handles all data types automatically
  • Supports expressions and method calls
  • Powerful formatting options

❌ Disadvantages:

  • Slightly more advanced concept for absolute beginners
  • Requires Python 3.6+ (but this is standard now)


← Back to where you were | → Start the course from the beginning


Worked example

Let’s see how to output the same output with the different methods. The code needs to print out the name of the app and the number of users it has as given by the variables app_name and num_users:

# Given data
app_name = "Teaching app"
num_users = 200

Output:

Teaching app with 200 users.

Using + operator:

message = (app_name + " with " str(num_users) " users.")
print(message)
# Output: Teaching app with 200 users.

Using , in print:

print(app_name, "with", num_users, "users.")
# Output: Teaching app with 200 users.

Using f-strings:

message = (f"{app_name} with {num_users}")
print(message)
# Output: Teaching app with 200 users.


← Back to where you were | → Start the course from the beginning


Common patterns and further comparison examples

1. User Greeting Patterns

# Pattern: Welcome message with personalization
name = input("What's your name? ")

# Method comparison:
print("Welcome,", name, "to our app!")                    # Comma method
print("Welcome, " + name + " to our app!")               # Plus method  
print(f"Welcome, {name} to our app!")                   # F-string method (best)

2. Score display patterns

# Pattern: Showing game statistics
correct = 8
total = 10
percentage = (correct / total) * 100

# Method comparison:
print("Score:", correct, "/", total, "(" + str(percentage) + "%)")  # Mixed methods
print("Score: " + str(correct) + "/" + str(total) + " (" + str(percentage) + "%)") # All plus
print(f"Score: {correct}/{total} ({percentage:.1f}%)")              # F-string (best)

3. Menu display patterns

# Pattern: Creating formatted menus
app_name = "Flashcard Master"
version = "2.1"

# F-string method (recommended):
menu = f"""
╔══════════════════════════════════╗
║  {app_name} v{version}           ║  
╠══════════════════════════════════╣
║  1. Start Practice Session       ║
║  2. View Statistics              ║
║  3. Settings                     ║
║  4. Exit                         ║
╚══════════════════════════════════╝
"""
print(menu)

4. Data validation messages

# Pattern: Error messages with context
min_cards = 1
max_cards = 50
user_input = 75

if user_input > max_cards:
    # F-string makes this very readable:
    error_msg = f"Error: {user_input} is too many cards. Please choose between {min_cards} and {max_cards}."
    print(error_msg)
    # Output: Error: 75 is too many cards. Please choose between 1 and 50.


← Return to where you were | → Start the course from the beginning


When to Use Each Method

Use + operator when:

  • You’re just starting to learn and want something simple
  • You’re concatenating just 2-3 simple strings
  • You need to build strings piece by piece in a loop
# Building a string in a loop
result = ""
for i in range(1, 4):
    result = result + str(i) + " "
print(result)  # Output: 1 2 3 

Use , in print when:

  • You want quick output for debugging
  • You have simple messages with mixed data types
  • You don’t need to save the result to a variable
# Quick debugging output
x = 10
y = 20
print("Debug:", x, y, x+y)  # Quick and easy

Use f-strings when:

  • You want clean, professional code (most of the time!)
  • You need to format numbers or data
  • You’re building complex messages
  • You want the most readable code
# Professional, clean code
user_data = {
    "name": "Alex",
    "progress": 0.85,
    "level": 7
}

status = f"Welcome {user_data['name']}! You're {user_data['progress']:.1%} complete at level {user_data['level']}."
print(status)
# Output: Welcome Alex! You're 85.0% complete at level 7.


← Back to where you were | → Start the course from the beginning


Best practices and style guidelines

1. Consistency is key

Pick one method for your project and stick with it:

# ❌ Inconsistent - hard to read
print("Hello,", name)
message = "Your score is " + str(score) + " points"
result = f"Final result: {total_score}"

# ✅ Consistent - much cleaner
print(f"Hello, {name}")
message = f"Your score is {score} points"
result = f"Final result: {total_score}"

2. Use F-Strings for complex formatting

# ✅ F-strings shine with complex data
student_data = {
    "name": "Emma",
    "scores": [85, 92, 78, 95],
    "grade_level": 10
}

report = f"""
Student Report for {student_data['name']}
Grade Level: {student_data['grade_level']}
Average Score: {sum(student_data['scores'])/len(student_data['scores']):.1f}
Best Score: {max(student_data['scores'])}
Total Assignments: {len(student_data['scores'])}
"""

3. Break Long Lines for Readability 📏

# ❌ Too long - hard to read
message = f"Congratulations {student_name}! You completed {total_exercises} exercises with {correct_answers} correct answers, achieving a {(correct_answers/total_exercises)*100:.1f}% success rate!"

# ✅ Broken into readable chunks
message = (f"Congratulations {student_name}! "
           f"You completed {total_exercises} exercises with {correct_answers} correct answers, "
           f"achieving a {(correct_answers/total_exercises)*100:.1f}% success rate!")


← Back to where you were | → Start the course from the beginning


Summary: Quick Reference Guide

Method Syntax Best For Example
+ operator "text" + variable + "text" Simple concatenation "Hello " + name
, in print print("text", variable, "text") Quick output, debugging print("Score:", score)
F-strings f"text {variable} text" Professional code, formatting f"Hello {name}!"


← Back to where you were | → Start the course from the beginning