Skip to content
Home » Blog » Master Python String Formatting: Complete Guide

Master Python String Formatting: Complete Guide

What is String Formatting?

String formatting is also known as formatted string construction. It is an operation that consists of building a string containing variable information by inserting values into a predetermined string format or design. It allows dynamic string composition without the necessity of concatenating values manually.

If you have to print a person’s name and age. You may do it like this:

name = "Alice"
age = 30
print("Name: " + name + ", Age: " + str(age))

But honestly, that looks a bit clunky.

Now look at this version:

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

Much cleaner, right?

It’s not just for printing names and ages either. You can use it when you need to:

  • Add numbers with decimal places
  • Format dates neatly
  • Align text in columns
  • Pad values with zeros or spaces
  • Or even make your output look like a table

Python gives us a few ways to do this:

  • F-strings — these are my go-to. If you’re using Python 3.6 or later, they’re fast and super readable.
  • .format() method — still useful, especially when you need a bit more control.
  • % formatting — old-school, but you’ll still run into it in older codebases.
  • And template strings — great when you’re working with user input and want to keep things safe.

At the end of the day, string formatting is all about making your output look clean and professional — without turning your code into a mess of quotes and plus signs.

Now let’s explore F-strings

F-strings — My Go-To Choice for String Formatting

If you’re using Python 3.6 or newer, f-strings (short for formatted string literals) will probably be your favorite method of string formatting. Personally, they’re my top choice — and the reasons why are good ones: they’re quick, readable, and compact.

Let’s understand why.

Diagram explaining how f-strings work in Python, showing variable substitution inside a string using curly braces.
Visual breakdown of Python f-strings — how variables are embedded directly in string literals using curly braces.

What Are f-strings?

An f-string is a string that starts with the character f or F, and you can insert Python expressions directly within the string with curly braces {}.

Rather than constructing strings by hand or with .format(), f-strings allow you to insert variables, function calls, or math inline — making the code much more readable and maintainable.

Why I Prefer f-strings

Here’s what makes f-strings my default choice in most projects:

1. Simplicity and Readability

You can clearly see where the variables are used — right inside the string.

name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.")

Output:

My name is Alice and I am 30 years old.

There’s no guesswork, no juggling of positions, and no need to reference arguments by index or key. It’s exactly what you see.

2. Faster Performance

Internally, f-strings are compiled at runtime, which means they’re generally faster than .format() or % formatting. When you’re formatting strings inside loops or performance-sensitive code, this matters.

3. Supports Expressions

You’re not limited to variables. You can run any valid Python expression inside the {}.

x = 5
y = 3
print(f"The sum of {x} and {y} is {x + y}.")

Output:

The sum of 5 and 3 is 8.

This avoids creating temporary variables just to show a value.

4. Great for Formatting Numbers

You can apply number formatting, alignment, padding, and more — all directly inside the f-string.

price = 1234.567
print(f"Total: ${price:,.2f}")

Output:

Total: $1,234.57

Here:

  • :, inserts a thousands separator
  • .2f rounds to two decimal places

It’s concise and self-explaining.

5. Cleaner Than Alternatives

Compare the same output using different methods:

Using .format()

"Total: ${:,.2f}".format(price)

Using f-string

f"Total: ${price:,.2f}"

The f-string version is shorter, more direct, and easier to follow.

When Should You Use f-strings?

F-strings are ideal for:

  • Logging and printing output
  • Debugging variable values
  • Reports, dashboards, or result summaries
  • Whenever you need clean, readable, dynamic strings

As long as you’re working with Python 3.6 or later, they are generally the optimal choice for string formatting.

Limitations to Be Aware Of

Although f-strings are powerful, they do have some restrictions:

They don’t work with Python 2.x or versions prior to 3.6.

They execute expressions immediately — which is wonderful for power, but you need to be careful when working with untrusted data (e.g., in web development).

You can’t reuse a placeholder by name — you’d need to retype the same variable again if necessary multiple times.

Summary

F-strings are quick, readable, and expressive.
If you’re working with Python 3.6 or higher, they streamline your string formatting and make your code cleaner.

That’s why — for me and for many — f-strings are the first choice when dynamically constructing strings.

Now, Let’s have a look at the .format() method — how it works, when to use it, and why it can still be really useful, especially when you require structured and flexible string building.

.format() Method — A Detailed Explanation

What Is the .format() Method in Python?

The .format() method is a Python built-in string method that enables you to place values within a string with the use of placeholders expressed as curly braces {}.

Introduced in Python 2.7 and 3.0, it was originally designed to replace the older % formatting method and remains a widely used approach, especially in situations where:

  • You need better control over formatting
  • You want to use named variables
  • If You’re working with dictionaries or dynamic content and
  • You want the same placeholder reused multiple times
Illustration showing how the format() method inserts values into placeholders in a Python string using curly braces.
Understanding the format() method in Python — inserting values into strings using indexed or named placeholders.

Basic Syntax

"template string with {} placeholders".format(values)

Every {} is replaced by an argument passed to the .format() method.

1. Positional Formatting (by order)

msg = "Hello, {}, you have {} new messages."
result = msg.format("Alice", 3)
print(result)

Output:

Hello, Alice, you have 3 new messages.
  • The first {} receives “Alice”
  • The second {} receives 3

You can also mention the position by name:

msg = "First: {0}, Second: {1}, Again First: {0}"
print(msg.format("X", "Y"))

Output:

First: X, Second: Y, Again First: X

Here, {0} and {1} are argument positions.

2. Named Placeholders (Keyword Arguments)

This is one of .format()’s strongest features:

msg = "Name: {name}, Score: {score}"
print(msg.format(name="Bob", score=95))

Output:

Name: Bob, Score: 95
  • This makes it easy to neatly specify what values go where.
  • Very useful when working with lots of values or dynamically populated data.

3. Formatting Values (Numbers, Padding, Alignment)

Example: Floating-point precision

price = 1234.56789
msg = "Price: {:.2f}".format(price)
print(msg)

Output:

Price: 1234.57
  • :.2f formats the number with 2 decimal places

Example: Padding and Alignment

print("{:<10} | {:>5}".format("Item", 25))

Output:

Item       |    25
  • <10 means left-align in a 10-character space
  • >5 means right-align in a 5-character space

4. Using Dictionaries with .format()

If your data is stored in a dictionary, you can unpack it into the string:

info = {"name": "Emma", "marks": 91}
msg = "Student: {name}, Marks: {marks}"
print(msg.format(**info))

Output:

Student: Emma, Marks: 91

The ** operator unpacks the dictionary into keyword arguments.

5. Reusing and Reordering Variables

You can repeat the same variable multiple times, or reorder them:

template = "Subject: {sub}, Marks: {marks}, {sub} is your favorite."
print(template.format(sub="Math", marks=95))

Output:

Subject: Math, Marks: 95, Math is your favorite.

This is not possible with f-strings unless you store the value in a separate variable.

When Is .format() More Useful Than f-strings?

SituationWhy .format() Helps
Older Python versionsWorks in Python 2.7 and 3.x
Dynamic templatesEasier when your template comes from outside (like files or UI)
Reusing valuesLets you repeat or rearrange variables in the string
Dictionaries or mappingsSupports **dict unpacking into placeholders
Formatting without expression evaluationGood when you want structure without runtime expression execution (e.g., internationalization systems)

What is % formatting in Python?

Percent formatting is an older string formatting technique that utilizes the % operator to place values inside a string. You insert the format specifiers (such as %s, %.2f, etc.) within the string, and then use % followed by a tuple of the values you would like to place inside.

Even though it’s older, this technique is still compatible in contemporary Python.

Diagram showing how Python’s % string formatting works with placeholders like %s and %d for inserting values.
Python % Formatting Explained — employing %s, %d, and other format specifiers to insert values inside strings.

Example Code:

language = "Python"
version = 3.11
message = "We are learning %s version %.2f" % (language, version)
print(message)

Step-by-Step Breakdown:

1. Format String:

"We are learning %s version %.2f"

This is the template string. It has two placeholders:

  • %s: for a string
  • %.2f: for a floating-point number, rounded to 2 decimal places

2. Variables:

language = "Python"
version = 3.11
  • language is a string
  • version is a float

3. Substitution using %:

% (language, version)
  • The values are put in a tuple, in the same order as the placeholders in the string.
  • Python substitutes %s with “Python”.
  • It substitutes %.2f with the number 3.11, rounded to two decimal places

4. Final Output:

We are learning Python version 3.11

Understanding the Format Specifiers

Format CodeMeaningExample
%sString"Python"
%dInteger (decimal)42
%fFloating-point number (default 6 decimals)3.141593
%.2fFloat with 2 decimal places3.14
%x / %XHexadecimal0x1f or 0X1F

Another Example:

name = "Alice"
marks = 88.6789
result = "Student: %s | Marks: %.1f" % (name, marks)
print(result)

Output:

Student: Alice | Marks: 88.7
  • %s → inserts the string Alice
  • %.1f → inserts the float 88.6789 rounded to 1 decimal place

Summary

What Are Template Strings?

Template strings are one method of string creation that involves variables. They are from the string module in Python. Rather than using {} like f-strings or .format(), you use a dollar sign and a variable name as follows:

from string import Template

t = Template("Hello, $name!")
print(t.substitute(name="Alice"))

Output:

Hello, Alice!
Visual showing how Python’s Template strings use $-based placeholders and the substitute() method for formatting.
How Template Strings Work in Python — using $ placeholders with the Template class for safe string formatting.

Why Use Template Strings?

1. Safer When Handling User Input

When you let users input data (e.g., completing a form or typing into a chat box), you can’t always be sure what they’ll type. If you use f-strings or .format() on that input directly, and you’re not paying attention, it could lead to issues — such as running unwanted code.

Template Strings circumvent this threat by handling all user input as plain text. They do not attempt to execute it, compute it, or interpret it as a command.

Example:

from string import Template

user_input = "__import__('os').system('rm -rf /')"  # harmful input
template = Template("User typed: $text")
print(template.substitute(text=user_input))

Output:

User typed: __import__('os').system('rm -rf /')

It simply prints the text — it does not execute any commands.

How Template Strings Work

  1. You define a string and pass variables with a dollar sign in front of them, such as $name.
  2. You pass in the values using substitute().

Example:

from string import Template

message = Template("Welcome, $user! You have $messages new messages.")
print(message.substitute(user="Tom", messages="3"))

Output:

Welcome, Tom! You have 3 new messages.

What If You Forget a Variable?

In case you forget to supply one of the variables, substitute() will throw an error. To prevent that, use safe_substitute() — it will keep the missing variable intact.

t = Template("Hello, $name! Your score is $score")
print(t.safe_substitute(name="John"))

Output:

Hello, John! Your score is $score

Escaping the Dollar Sign

If you need to display a dollar sign (say, $100), use two dollar signs $.

t = Template("Price: $$${amount}")
print(t.substitute(amount="25"))

Output:

Price: $25

When Should You Use Template Strings?

  • When working with user input
  • When creating email templates, SMS messages, or reports
  • If you need to prevent errors due to unknown or unsafe input you can use template strings
  • When you require simple and readable formatting

Summary

Template Strings:

  • Are defined using the Template class of the string module
  • Use $variable rather than {} or %s
  • Don’t execute any code, which makes them safe
  • Are excellent when you don’t want unanticipated behavior from user input

Conclusion

Python’s string formatting has come a long way since its development. Although all four approaches are acceptable, f-strings are the new, Pythonic way to do string formatting. They provide the optimal balance of readability, performance, and features.

Key takeaways:

  • Use f-strings for new Python 3.6+ projects
  • Use .format() when you need template reusability or backward compatibility
  • You can use % formatting sparingly, mainly for legacy code maintenance
  • Master format specifiers to create professional-looking output
  • Consider security implications when formatting user input

Practice these techniques in your own projects, and you’ll soon find yourself creating beautifully formatted strings with ease!

Python String Formatting Quiz

Quick Quiz: Python String Formatting

1. Which string formatting method is recommended in Python 3.6+?

2. Which method is safest when working with user input?

3. Which method is considered old-school but still seen in legacy code?

4. Which method uses `{}` as placeholders without any prefix?

5. Which formatting method requires a format specifier like %s or %d?

6. Which of the following is valid f-string syntax?

7. Which method is best for readability and performance?

8. Which string formatting method uses `$` for placeholders?

9. Which method allows evaluating expressions directly inside the string?

10. Which method is not affected by user input injection?

Python String Formatting FAQs

Frequently Asked Questions: Python String Formatting

1. What is the most recommended string formatting method in Python 3.6+?

F-strings are the most recommended. They’re fast, readable, and concise.

2. When should I use the .format() method?

Use .format() when you need dynamic placeholder positions or are working with older versions of Python.

3. Is % formatting still used?

Yes, it’s considered old-school but still common in legacy codebases or short scripts.

4. Are f-strings safer than template strings?

No. Template strings are safer when dealing with user input, as they don’t evaluate expressions.

5. Can I use expressions inside f-strings?

Absolutely. You can include variables and expressions directly inside curly braces, like f"{x + y}".
External Resources: Python String Formatting

External Resources

About The Author

Leave a Reply

Your email address will not be published. Required fields are marked *

  • Rating