Skip to main content

Command Palette

Search for a command to run...

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

Updated
โ€ข4 min read
F-Strings in Python: The Ultimate Guide to String Formatting
N

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.

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.

More from this blog

Naveen P.N's Tech Blog

94 posts