Have you ever tried to print a mix of text and variable values and ended up with messy code? Python’s f-strings, also known as formatted string literals, are a modern and powerful way to embed expressions inside strings, making your output clean and readable.
✨ What Are F-Strings and How Do They Work?
An f-string is created by prefixing a string with the letter f
. Inside this string, you can place variables or any Python expression directly inside curly braces {}
, and Python will automatically replace them with their current values. For example: name = "Alice"; print(f"Hello, {name}!")
will display “Hello, Alice!”. This is much cleaner than using string concatenation.
💰 Formatting Numbers with F-Strings
F-strings truly shine when you need to format numbers. You can control things like the number of decimal places for a floating-point number. To do this, you add a colon :
followed by a format specifier inside the braces. For example, to round a number to two decimal places, you would use :.2f
. So, if price = 19.999
, print(f"The price is ${price:.2f}")
would output “The price is $20.00”.
📊 Aligning Text and Creating Tables
Another powerful feature is controlling the alignment and width of your output, which is perfect for creating tables. You can specify a minimum width for a value and align it to the left (<
), right (>
), or center (^
). For instance, f"{name:>10s}"
would right-align the `name` variable within a 10-character space. You can even add comma separators for large numbers automatically with :,d
for integers or :,.2f
for floats.
F-strings are the go-to method for string formatting in modern Python. They are fast, readable, and incredibly versatile, helping you create professional-looking output with minimal effort.
---
Stephenson, Ben. The Python Workbook: A Brief Introduction with Exercises and Solutions. 3rd ed., Springer, 2025.
More Topics
- How to Pass Command Line Arguments to Your Python Script
- Solving the Classic FizzBuzz Problem in Python: A Step-by-Step Tutorial
- How to Solve the Pythagorean Theorem with a Python Script
- What’s the Difference Between Syntax, Runtime, and Logic Errors in Python?
- What Are Dictionaries in Python and How Do You Use Them?
- Thinking Recursively: A Beginner’s Introduction to Recursion in Python
- How to Read and Write Files in Python