Skip to main content

F-Strings in Python: The Ultimate Guide to String Formatting

Updated 4 min readMarkdown
F-Strings in Python: The Ultimate Guide to String Formatting

Absolutely! Below is a complete and well-structured guide to F-strings in Python, covering everything from basic usage to advanced formatting, including real-world examples.


F-Strings in Python: A Complete Guide to Efficient String Formatting

Introduction to String Formatting in Python

String formatting is a fundamental concept in programming that allows developers to dynamically insert variables and expressions into text. Python offers various methods for formatting strings, but F-strings, introduced in Python 3.6, provide the most efficient, readable, and powerful way to format strings.

Traditional String Formatting Methods

Before F-strings, Python relied on several techniques:

  1. String Concatenation (+ Operator)
    Concatenating strings manually can lead to messy and inefficient code.

     name = "Rahul"
     message = "Hello, " + name + "!"
     print(message)  # Output: Hello, Rahul!
    
  2. C-Style % Formatting
    A method inspired by C-style formatting, but it lacks flexibility.

     name = "Rahul"
     age = 28
     print("Name: %s, Age: %d" % (name, age))
     # Output: Name: Rahul, Age: 28
    
  3. .format() Method
    .format() introduced a structured way to insert values, but can be verbose.

     name = "Rahul"
     age = 28
     print("Name: {}, Age: {}".format(name, age))
     # Output: Name: Rahul, Age: 28
    

Why Use F-Strings?

F-strings solve the limitations of previous methods by offering:

  • Cleaner syntax

  • Improved readability

  • Faster execution

  • Dynamic expression embedding


Basic Syntax of F-Strings

An F-string is prefixed with f before the quotes, and expressions are enclosed in {}.

name = "Rahul"
print(f"Hello, {name}!")  # Output: Hello, Rahul!

You can use uppercase F as well:

print(F"Welcome, {name}!")

Embedding Expressions in F-Strings

F-strings allow embedding calculations, method calls, and inline operations:

a, b = 10, 20
print(f"The sum of {a} and {b} is {a + b}")  # Output: The sum of 10 and 20 is 30

Using built-in functions:

text = "Python"
print(f"The length of '{text}' is {len(text)}")  # Output: The length of 'Python' is 6

Using Functions Inside F-Strings

You can call functions inside F-strings:

def greet():
    return "Good morning!"

print(f"Greeting: {greet()}")  # Output: Greeting: Good morning!

Advanced Number Formatting in F-Strings

1. Controlling Decimal Places

pi = 3.1415926535
print(f"Pi rounded to 2 decimal places: {pi:.2f}")  # Output: Pi rounded to 2 decimal places: 3.14

2. Adding Commas in Large Numbers

population = 1380004385
print(f"Population of India: {population:,}")  # Output: Population of India: 1,380,004,385

3. Displaying Percentages

discount = 0.15
print(f"Discount: {discount:.0%}")  # Output: Discount: 15%

Multi-Line F-Strings

For multi-line formatted strings, use triple quotes f""" """:

name = "Mahesh"
age = 30
city = "Bengaluru"

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

Output:

Name: Mahesh
Age: 30
City: Bengaluru

Accessing Dictionaries and Lists in F-Strings

Directly access dictionary keys and list elements:

student = {'name': 'Meera', 'marks': 92}
print(f"Student: {student['name']}, Marks: {student['marks']}")  # Output: Student: Meera, Marks: 92

scores = [85, 90, 95]
print(f"Top score: {scores[0]}")  # Output: Top score: 85

Escaping Braces in F-Strings

To display {} literally, use double braces:

print(f"Use {{ and }} for displaying braces in text.")
# Output: Use { and } for displaying braces in text.

Limitations of F-Strings

  • Requires Python 3.6+ – Older versions do not support F-strings.

  • Cannot contain backslashes \ inside expressions – Leads to parsing issues.

  • Not ideal for internationalization (i18n) – .format() is preferred for localization.


F-Strings Functions & Special Uses

1. Object Representation (repr())

F-strings can use !r for object representation.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __repr__(self):
        return f"Person(name={self.name!r}, age={self.age})"

p = Person("Aditi", 27)
print(p)  # Output: Person(name='Aditi', age=27)

2. Padding & Alignment

F-strings allow text alignment using <, ^, and >.

product = "Laptop"
print(f"|{product:<10}|")  # Left-align  |Laptop    |
print(f"|{product:^10}|")  # Center-align |  Laptop  |
print(f"|{product:>10}|")  # Right-align  |    Laptop|

3. Binary, Hexadecimal, and Octal Formatting

num = 255
print(f"Hex: {num:#x}, Binary: {num:#b}, Octal: {num:#o}")
# Output: Hex: 0xff, Binary: 0b11111111, Octal: 0o377

Real-World Applications of F-Strings

1. Formatting Financial Data

salary = 85000.5
tax_rate = 0.18
tax_amount = salary * tax_rate

print(f"Salary: ₹{salary:,.2f}")
print(f"Tax at {tax_rate:.0%}: ₹{tax_amount:,.2f}")

Output:

Salary: ₹85,000.50
Tax at 18%: ₹15,300.09

2. Displaying Weather Information

city = "Mumbai"
temperature = 29.5
humidity = 72

print(f"Weather in {city}: {temperature}°C with {humidity}% humidity.")

Output:
Weather in Mumbai: 29.5°C with 72% humidity.


3. Logging System Events

import datetime

now = datetime.datetime.now()
print(f"[{now:%Y-%m-%d %H:%M:%S}] Server Running Smoothly.")

Output:
[2025-05-05 12:01:00] Server Running Smoothly.

About the author

  • I am a Tech Enthusiast having 13+ years of experience in 𝐈𝐓 as a 𝐂𝐨𝐧𝐬𝐮𝐥𝐭𝐚𝐧𝐭, 𝐂𝐨𝐫𝐩𝐨𝐫𝐚𝐭𝐞 𝐓𝐫𝐚𝐢𝐧𝐞𝐫, 𝐌𝐞𝐧𝐭𝐨𝐫, with 12+ years in training and mentoring in 𝐒𝐨𝐟𝐭𝐰𝐚𝐫𝐞 𝐄𝐧𝐠𝐢𝐧𝐞𝐞𝐫𝐢𝐧𝐠, 𝐃𝐚𝐭𝐚 𝐄𝐧𝐠𝐢𝐧𝐞𝐞𝐫𝐢𝐧𝐠, 𝐓𝐞𝐬𝐭 𝐀𝐮𝐭𝐨𝐦𝐚𝐭𝐢𝐨𝐧 𝐚𝐧𝐝 𝐃𝐚𝐭𝐚 𝐒𝐜𝐢𝐞𝐧𝐜𝐞. I have 𝒕𝒓𝒂𝒊𝒏𝒆𝒅 𝒎𝒐𝒓𝒆 𝒕𝒉𝒂𝒏 10,000+ 𝑰𝑻 𝑷𝒓𝒐𝒇𝒆𝒔𝒔𝒊𝒐𝒏𝒂𝒍𝒔 and 𝒄𝒐𝒏𝒅𝒖𝒄𝒕𝒆𝒅 𝒎𝒐𝒓𝒆 𝒕𝒉𝒂𝒏 500+ 𝒕𝒓𝒂𝒊𝒏𝒊𝒏𝒈 𝒔𝒆𝒔𝒔𝒊𝒐𝒏𝒔 in the areas of 𝐒𝐨𝐟𝐭𝐰𝐚𝐫𝐞 𝐃𝐞𝐯𝐞𝐥𝐨𝐩𝐦𝐞𝐧𝐭, 𝐃𝐚𝐭𝐚 𝐄𝐧𝐠𝐢𝐧𝐞𝐞𝐫𝐢𝐧𝐠, 𝐂𝐥𝐨𝐮𝐝, 𝐃𝐚𝐭𝐚 𝐀𝐧𝐚𝐥𝐲𝐬𝐢𝐬, 𝐃𝐚𝐭𝐚 𝐕𝐢𝐬𝐮𝐚𝐥𝐢𝐳𝐚𝐭𝐢𝐨𝐧𝐬, 𝐀𝐫𝐭𝐢𝐟𝐢𝐜𝐢𝐚𝐥 𝐈𝐧𝐭𝐞𝐥𝐥𝐢𝐠𝐞𝐧𝐜𝐞 𝐚𝐧𝐝 𝐌𝐚𝐜𝐡𝐢𝐧𝐞 𝐋𝐞𝐚𝐫𝐧𝐢𝐧𝐠. I am interested in 𝐰𝐫𝐢𝐭𝐢𝐧𝐠 𝐛𝐥𝐨𝐠𝐬, 𝐬𝐡𝐚𝐫𝐢𝐧𝐠 𝐭𝐞𝐜𝐡𝐧𝐢𝐜𝐚𝐥 𝐤𝐧𝐨𝐰𝐥𝐞𝐝𝐠𝐞, 𝐬𝐨𝐥𝐯𝐢𝐧𝐠 𝐭𝐞𝐜𝐡𝐧𝐢𝐜𝐚𝐥 𝐢𝐬𝐬𝐮𝐞𝐬, 𝐫𝐞𝐚𝐝𝐢𝐧𝐠 𝐚𝐧𝐝 𝐥𝐞𝐚𝐫𝐧𝐢𝐧𝐠 new subjects.

No comments yet. Be the first to comment.

More from this blog