Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors
Filter by Categories
About Article
Analyze Data
Archive
Best Practices
Better Outputs
Blog
Code Optimization
Code Quality
Command Line
Daily tips
Dashboard
Data Analysis & Manipulation
Data Engineer
Data Visualization
DataFrame
Delta Lake
DevOps
DuckDB
Environment Management
Feature Engineer
Git
Jupyter Notebook
LLM
LLM
Machine Learning
Machine Learning
Machine Learning & AI
Manage Data
MLOps
Natural Language Processing
NumPy
Pandas
Polars
PySpark
Python Tips
Python Utilities
Python Utilities
Scrape Data
SQL
Testing
Time Series
Tools
Visualization
Visualization & Reporting
Workflow & Automation
Workflow Automation

Python f-strings: The Modern Way to Format Strings

Table of Contents

Python f-strings: The Modern Way to Format Strings

F-strings (formatted string literals) have transformed string formatting in Python since their introduction in Python 3.6. Let’s explore some useful ways to use f-strings.

1. Number Formatting

Decimal Places

When working with floating-point numbers, controlling decimal places is crucial for readability:

ratio = 0.8544
print(f'{ratio:.2f}')  # Output: 0.85

Large Numbers

Make big numbers readable with automatic comma separation:

num = 100000000
print(f"{num:,}")  # Output: 100,000,000

2. Percentage Formatting

Converting decimals to percentages is a common task in data analysis and reporting:

ratio = 0.8544
print(f"{ratio:.1%}")  # Output: 85.4%

3. Date and Time Formatting

F-strings make date formatting intuitive and readable:

from datetime import datetime
date = datetime(2022, 1, 1, 15, 30, 45)
print(f"{date:%I:%M %p} on {date:%A}")  # Output: 03:30 PM on Saturday

4. Debug Printing

One of the most useful features for debugging is the ability to display variable names alongside their values:

for i in range(3):
    print(f"{i=}")
# Output:
# i=0
# i=1
# i=2

Leave a Comment

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

0
    0
    Your Cart
    Your cart is empty
    Scroll to Top

    Work with Khuyen Tran

    Work with Khuyen Tran