0%

8- String Concatenation & Formatting

Mixing strings with variables. Combining words with numbers. Creating clean, readable messages. Three ways to do it. Each with its own magic.

You have a name. You have a score. You want to say “Hello, [name]! Your score is [score].” How do you combine them? Python gives you several ways to build strings from pieces. Some are old but still work. Some are new and elegant. Some are fast. Some are readable. You will learn all of them because each has its place in a programmer’s toolkit. The techniques you will learn: concatenation with +, the % operator (old style), the .format() method, and f-strings (modern magic).

🕯️ Magic Note

F-strings are the newest and most recommended way to format strings in Python. They are fast, readable, and elegant. But you will see old code using the other methods, so understanding all of them is important. Choose f-strings for your own code whenever possible.

Method 1: Concatenation with +
The simplest way to combine strings is using the + operator. You already learned this. But there is a problem: everything you join must be a string.

Python

name = “Feloriya”

score = 100

# This works (all strings)

message = “Hello, ” + name + “!”

print(message) # Hello, Feloriya!

# This fails (string + integer)

# message = “Score: ” + score # TypeError

# Fix: convert number to string

message = “Score: ” + str(score)

print(message) # Score: 100

⚠️ Concatenation with + becomes inefficient for many pieces. Each + creates a new string. For joining many strings (like in a loop), use .join() instead.
Method 2: The % Operator (Old Style)
Before Python 3, the % operator was the primary way to format strings. It is borrowed from C’s printf. You still see it in old code. The pattern is “format string” % (values).
Format SpecifierWhat It DoesExample
%sString (or any type converted to string)“Hello %s” % “Feloriya” → “Hello Feloriya”
%dInteger“Age: %d” % 25 → “Age: 25”
%fFloat“Price: %f” % 19.99 → “Price: 19.990000”
%.2fFloat with 2 decimal places“Price: %.2f” % 19.99 → “Price: 19.99”
%xHexadecimal“Hex: %x” % 255 → “Hex: ff”

Python

name = “Feloriya”

age = 25

price = 19.99

# Basic formatting

print(“Hello %s” % name) # Hello Feloriya

print(“Age: %d” % age) # Age: 25

print(“Price: %.2f” % price) # Price: 19.99

# Multiple values (must be in a tuple)

print(“Name: %s, Age: %d” % (name, age)) # Name: Feloriya, Age: 25

💡 The % operator works but is considered old style. Use it only for simple formatting or when maintaining old code. For new code, use f-strings or .format().
Method 3: The .format() Method
The .format() method was introduced in Python 3. It is more powerful than % and more readable. Placeholders {} in the string are replaced by the arguments passed to .format().

Python

name = “Feloriya”

age = 25

score = 95.5

# Positional arguments

print(“Hello {}!”.format(name))

# Hello Feloriya!

print(“Name: {}, Age: {}”.format(name, age))

# Name: Feloriya, Age: 25

# Positional with indices (can repeat)

print(“{0} {0} {0}”.format(“ha”))

# ha ha ha

# Keyword arguments

print(“Name: {n}, Age: {a}”.format(n=name, a=age))

# Name: Feloriya, Age: 25

🕯️ Magic Note

You can specify formatting inside the placeholders. For example: {:.2f} for two decimal places, {:d} for integers, {:10} for width, {:>10} for right alignment.

Python

# Format specifiers inside {}

pi = 3.14159265

print(“Pi: {:.2f}”.format(pi)) # Pi: 3.14

print(“Pi: {:.4f}”.format(pi)) # Pi: 3.1416

# Width and alignment

print(“{:>10}”.format(“right”)) # right

print(“{:<10}”.format(“left”)) # left

print(“{:^10}”.format(“center”)) # center

# Numbers with width and padding

print(“{:05d}”.format(42)) # 00042

print(“{:+,}”.format(1000000)) # +1,000,000

Method 4: F-Strings (The Modern Way)
F-strings (formatted string literals) were introduced in Python 3.6. They are the most readable, fastest, and most recommended way to format strings. Put an f before the opening quote and use {variable} directly inside.

Python

name = “Feloriya”

age = 25

score = 95.5

# Basic f-string

print(f”Hello {name}!”)

# Hello Feloriya!

print(f”Name: {name}, Age: {age}”)

# Name: Feloriya, Age: 25

# You can put expressions inside {}

print(f”Next year you will be {age + 1}”)

# Next year you will be 26

print(f”Score: {score:.2f}”)

# Score: 95.50

# Call methods inside {}

print(f”Uppercase: {name.upper()}”)

# Uppercase: FELORIYA

🕯️ Magic Note

F-strings are evaluated at runtime. You can put any valid Python expression inside the curly braces: {len(name)}, {name.strip().lower()}, {a + b * c}. This makes them incredibly powerful.

Python

# Complex expressions in f-strings

x = 5

y = 10

print(f”{x} + {y} = {x + y}”)

# 5 + 10 = 15

words = [“magic”, “spells”, “conjure”]

print(f”Number of words: {len(words)}”)

# Number of words: 3

# Conditional inside f-string

score = 85

print(f”Result: {‘Pass’ if score >= 60 else ‘Fail’}”)

# Result: Pass

💡 F-strings are available only in Python 3.6 and later. If your code needs to run on older Python versions (3.5 or earlier), use .format() or % instead. For modern Python, always prefer f-strings.
Formatting Numbers: A Deeper Look
Each method has its own way of formatting numbers. Here is a comparison.

Python

num = 1234.56789

percentage = 0.856

large = 1234567

# Two decimal places

print(f”{num:.2f}”) # 1234.57

print(“{:.2f}”.format(num)) # 1234.57

print(“%.2f” % num) # 1234.57

# Percentage

print(f”{percentage:.1%}”) # 85.6%

# Comma as thousands separator

print(f”{large:,}”) # 1,234,567

# Width and padding

print(f”{num:10.2f}”) # 1234.57 (width 10, right aligned)

print(f”{num:<10.2f}”) # 1234.57 (left aligned)

Multi-line Strings and Formatting
Sometimes you need to format long messages that span multiple lines. Python handles this beautifully.

Python

name = “Feloriya”

skill = “Python”

level = “intermediate”

# Multi-line f-string (with triple quotes)

message = f”””

=== Wizard Profile ===

Name: {name}

Skill: {skill}

Level: {level}

====================

“””

print(message)

Performance Comparison
Different methods have different speeds. F-strings are the fastest. .format() is slightly slower. % is similar to .format(). Concatenation with + is the slowest, especially for many parts. For most code, the difference does not matter. Choose readability first. But if you are formatting thousands of strings in a loop, f-strings are your best choice.
💡 If you need to join many strings (like a list of words), use separator.join(list). It is much faster than any formatting method or concatenation in a loop.
Common Mistakes with String Formatting
  • Forgetting the f prefix: “Hello {name}” prints literally, not the value
  • Mixing up % syntax: “%s %d” % (text, num) requires parentheses
  • Using f-strings in Python versions older than 3.6 (they will cause SyntaxError)
  • Forgetting to convert numbers to strings with + concatenation
  • Putting too many expressions inside f-string braces (keep them simple and readable)
  • Using .format() with wrong number of arguments (too few or too many)
⚠️ When using f-strings, the expressions inside {} are evaluated immediately. If a variable changes later, the f-string does not update. The formatted string is created once at that moment. This is usually what you want, but be aware of it.
Which Method Should You Use?
MethodWhen to UseExample
+Very simple joins (2-3 parts, all strings already)“Hello ” + name
%Old code maintenance or very simple formatting“Age: %d” % age
.format()Python 3.5 or earlier, or when you need advanced formatting options“Name: {}”.format(name)
f-stringsPython 3.6+ (most code today) – always prefer thisf”Name: {name}”
Check Your Understanding
  • Write an f-string that prints “Hello, [name]! You are [age] years old.”
  • How do you format a float to two decimal places using an f-string?
  • What happens if you forget the f before an f-string?
  • Why is .join() better than + for joining many strings?
  • Convert “Score: {}” to an f-string.
  • What is the output of f”Value: {10 * 2}”?

⚡ Whisper

A formatted string is a message waiting to be completed. You write the skeleton with empty spaces. Later, you fill those spaces with names, numbers, and whispered secrets. The old ways use % like ancient runes. The new ways use {} like open hands. But the f-string is the true magic of our time. You speak the variable name directly inside the string, and Python understands. Choose your method wisely. But always choose readability. A clear message is worth more than a clever trick.

Related posts