Python String Formatting, F-Strings, Placeholders, and Modifiers
📌 Table of Contents
- Introduction
- Placeholders
- F-Strings (Formatted String Literals)
- Modifiers and Format Specifiers
- str.format() Method
- Old-Style % Formatting
- Advanced F-String Examples
- Exercises
- FAQs
- Conclusion
📘 Introduction
String formatting in Python is one of the most essential skills for any programmer. Properly formatted strings make your output readable, professional, and easy to maintain. Python offers multiple methods for string formatting, each with its own advantages. In this guide, we will cover everything from basic placeholders to advanced f-string operations.
By the end of this tutorial, you will understand:
- How to use placeholders to insert variables in strings
- F-strings (formatted string literals) and their power
- Modifiers for alignment, width, precision, and padding
- The
str.format()
method and its advanced uses - Old-style
%
formatting and when to use it - Performing operations and calling functions inside f-strings
- Exercises and FAQs for practice
🧩 Placeholders
Placeholders are markers inside strings that tell Python where to insert a variable or value. They are often represented as curly braces {}
and are a key component of both f-strings and str.format()
.
Examples:
fruit = "apple"
quantity = 5
print(f"I bought {quantity} {fruit}s today.")
I bought 5 apples today.
Indexed Placeholders with str.format()
:
print("I like {1} and {0}".format("Java", "Python"))
Named Placeholders:
print("Name: {name}, Country: {country}".format(name="John", country="USA"))
💡 F-Strings (Formatted String Literals)
F-strings, introduced in Python 3.6, allow embedding expressions directly inside string literals. They are prefixed with f
or F
and are currently the most readable and efficient way to format strings.
Syntax:
f"Text {expression}"
Example:
name = "Alice"
age = 28
print(f"My name is {name} and I am {age} years old.")
Operations Inside F-Strings:
F-strings allow you to perform calculations and operations directly inside the curly braces.
a = 5
b = 10
print(f"{a} + {b} = {a + b}")
print(f"Double of {b} is {b*2}")
5 + 10 = 15
Double of 10 is 20
Calling Functions in F-Strings:
You can also call functions or methods inside f-strings:
print(f"Uppercase: {'python'.upper()}")
print(f"Length: {len('Python')}")
print(f"Square: {pow(5,2)}")
Uppercase: PYTHON
Length: 6
Square: 25
⚙️ Modifiers and Format Specifiers
Modifiers help control the formatting of strings, including alignment, width, padding, precision, and type.
Alignment and Width:
Modifier | Description | Example | Output |
---|---|---|---|
< | Left align | f"{'Hi':<10 code="">10> | Hi |
> | Right align | f"{'Hi':>10}" | Hi |
^ | Center align | f"{'Hi':^10}" | Hi |
0 | Pad with zeros | f"{5:03}" | 005 |
Precision and Type:
Type | Description | Example | Output |
---|---|---|---|
d | Decimal integer | {:d} | 42 |
f | Fixed-point float | {:.2f} | 3.14 |
b | Binary | {:b} | 101010 |
o | Octal | {:o} | 52 |
x / X | Hexadecimal | {:x} | 2a |
e / E | Scientific notation | {:e} | 1.000000e+00 |
% | Percentage | {:.1%} | 75.0% |
s | String | {:s} | Hello |
🧮 str.format() Method
The str.format()
method is another way to format strings. It supports positional arguments, named arguments, and advanced formatting options.
print("My name is {} and I am {} years old.".format("Alice", 25))
print("I like {1} and {0}".format("Java", "Python"))
print("Name: {name}, Country: {country}".format(name="John", country="USA"))
📊 Old-Style % Formatting
This is the legacy formatting style using the %
operator.
name = "Alice"
age = 25
print("Name: %s, Age: %d" % (name, age))
🧩 Advanced F-String Examples
# Nested formatting
value = 123.4567
print(f"Value: {value:{10}.{6}}")
# Formatting dates
import datetime
today = datetime.date.today()
print(f"Today's date: {today:%B %d, %Y}")
# Multiline f-string
name = "Alice"
age = 25
print(f"""
Hello, {name}!
You are {age} years old.
""")
💪 Exercises
- Create an f-string that prints your full name and age.
- Format a float to 3 decimal places using f-strings.
- Use
str.format()
to display a table of 3 students and their grades. - Display the binary, octal, and hexadecimal of the number 42.
- Create a multiline f-string greeting message.
- Align text left, right, and center in 15-character wide fields.
- Call functions like
len()
andupper()
inside an f-string.
❓ FAQs
1. Difference between f-strings and str.format()?
F-strings allow inline expressions and are faster. str.format() is older but still used for compatibility.
2. Can we call functions inside f-strings?
Yes, any function or method can be called inside {}
.
3. Is % formatting still used?
It's legacy and not recommended for new projects.
4. How to align text?
Use <
, >
, ^
with optional width. Example: f"{text:^10}"
5. Can f-strings span multiple lines?
Yes, use triple quotes: f"""Multiline {var}"""
🧠Conclusion
Python string formatting is essential for readable and professional outputs. F-strings are the most efficient, allowing inline operations, function calls, and advanced formatting. Understanding placeholders, modifiers, and str.format() helps you write clean, maintainable code. This guide equips you to format numbers, strings, and dynamic content effectively. Practice exercises and examples reinforce the concepts and prepare you for real-world Python projects.
🔗 Related Tutorials
- Python Programming: A Beginner’s Guide
- Python Variables
- Python Data Types
- Python Strings
- Python Operators
- Python Lists
- Python Tuples
- Python Sets
- Python Dictionaries
- Python If...Else Statements and Conditions
- Python Match Statement
- Python Functions
- Python Lambda
- Python Arrays
- Python Classes & Objects
- Python Inheritance
- Python Iterators
- Python Polymorphism
- Python Scope
- Python Modules
- Python Datetime
- Python Math
- Python Exception Handling
- Python File Handling
- Python Generators & Itertools
- Python Decorators
- Python Exercises & Projects
- Python JSON
- Python RegEx Tutorial
- Python Try Except
© 2025 IT Tech Guide To Learn | Python Educational Tutorials
0 Comments