String Concatenation and Formatting
What is String Concatenation?
String concatenation means combining multiple strings together to create a longer string.
There are several ways to combine strings in Python, each with its own advantages and use cases.
Example:
first_name = "Alice"
last_name = "Smith"
# With '+' operator
print(first_name + " " + last_name ) # Output: Alice Smith
# With ','
print(first_name, last_name)
# With f-string
print(f"{first_name} {last_name}") # Output: Alice Smith
Try it:
first_name = "Alice"
last_name = "Smith"
# With '+' operator
print(first_name + " " + last_name ) # Output: Alice Smith
# With ','
print(first_name, last_name)
# With f-string
print(f"{first_name} {last_name}") # Output: Alice Smith
Method 1: The + Operator (String Addition)
The + symbol “adds” 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 = "Games"
version = "1.0"
title = app_name + " App " + "v" + version
print(title) # Output: Games App v1.0
Try it:
# 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 = "Games"
version = "1.0"
title = app_name + " App " + "v" + version
print(title) # Output: Games 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 becauseversionis afloat: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"
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!
# 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
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.
Try it:
# 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!
Try it:
length = 10
width = 5
print(f"The area is {length * width} square units")
score = 85
total = 100
print(f"You got {score/total*100}% 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}formatspriceto 2 decimal places- The
fmeans “float” (decimal number)
Try it:
length = 10
width = 5
print(f"The area is {length * width} square units")
score = 85
total = 100
print(f"You got {score/total*100}% correct!")
Percentages
E.g.
score = 0.875
print(f"Success rate: {score:.1%}") # As percentage
# Output: Success rate: 87.5%
{score:.1%}formatsscoreto a percentage with one decimal place- the
%symbol means percentage
Try it:
score = 0.875
print(f"Success rate: {score:.1%}")
Separators in large numbers
E.g.
population = 1234567
print(f"Population: {population:,}") # Add commas
# Output: Population: 1,234,567
{population:,}formatspopulationto a comma-split number- the
,symbol indicates that it should be displayed with the comma-splits
Try it:
population = 1234567
print(f"Population: {population:,}")
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
Try it:
name = "alice"
print(f"Hello, {name.title()}!") # Capitalize first letter
items = ["apple", "banana", "cherry"]
print(f"We have {len(items)} items: {', '.join(items)}")
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)
Worked example
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 = "Games app"
num_users = 200
Output:
Games app with 200 users.
Using + operator:
message = (app_name + " with " str(num_users) " users.")
print(message)
# Output: Games app with 200 users.
Using , in print:
print(app_name, "with", num_users, "users.")
# Output: Games app with 200 users.
Using f-strings:
message = (f"{app_name} with {num_users}")
print(message)
# Output: Games app with 200 users.
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!")
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.
Quick reference
| 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}!" |
