F-strings make it possible to insert variables and expressions directly inside a string. They were introduced in Python 3.6 and are now widely used for creating formatted and dynamic output.
In this article, you will learn what f-strings are, how they work, how to insert variables and expressions, and how to format different types of values using them.
Table of Contents
What are F-Strings in Python?
F-strings, also called formatted string literals, are a way of formatting strings in Python by placing an f or F before the opening quotation mark.
Variables and expressions can then be placed inside curly braces {}, and Python automatically replaces them with their corresponding values.
Example:
# Python program to demonstrate a basic f-string
name = "Rahul"
age = 18
# Inserting variables into an f-string
print(f"My name is {name} and I am {age} years old.")
Output:
My name is Rahul and I am 18 years old.
Explanation:
- The f before the string tells Python that it is an f-string.
- {name} is replaced with the value stored in the name variable.
- {age} is replaced with the value stored in the age variable.
- Python combines the text and variable values into a single string.
Why Use F-Strings?
F-strings provide a simple and convenient way to create formatted strings while keeping the code readable.
- Easy to Read: Variables can be placed directly inside the string, making the code easier to understand.
- Less Code: F-strings usually require less code than older methods such as string concatenation.
- Supports Expressions: You can perform calculations and use expressions directly inside curly braces.
- Easy Number Formatting: F-strings provide formatting options for decimal values, percentages, commas, and more.
- Useful for Dynamic Output: They make it easy to create messages whose content changes according to variable values.
Syntax of F-Strings
The basic syntax of an f-string is:
f"Text {variable}"
The f or F before the quotation marks tells Python to treat the string as an f-string.
Example:
# Python program to demonstrate the syntax of an f-string
name = "Python"
# Inserting the variable into the string
print(f"Welcome to {name} programming.")
Output:
Welcome to Python programming.
Explanation: Here, f identifies the string as an f-string. The variable name is placed inside {}. Python automatically replaces {name} with its stored value.
How F-Strings Work?
When Python encounters an f-string, it evaluates the expressions written inside curly braces {} and inserts their results into the string.
Example:
# Python program to understand how f-strings work
name = "Aman"
age = 20
# Inserting variable values into the f-string
message = f"{name} is {age} years old."
print(message)
Output:
Aman is 20 years old.
Explanation: Python evaluates {name} and {age} and replaces them with "Aman" and 20. The resulting text is then stored in the message variable.
Inserting Variables in F-Strings
One of the most common uses of f-strings is inserting variable values directly into a string. You can insert multiple variables in the same f-string.
Example:
# Python program to insert multiple variables into an f-string
name = "Rahul"
course = "Python"
duration = 3
# Displaying multiple variable values
print(f"{name} is learning {course} for {duration} months.")
Output:
Rahul is learning Python for 3 months.
Explanation: The f-string contains three variables: name, course, and duration. Python replaces each variable with its corresponding value.
Using Expressions Inside F-Strings
F-strings can contain more than just variables. You can also place expressions inside curly braces, and Python will calculate their results before displaying them.
Example:
# Python program to use an expression inside an f-string
a = 10
b = 5
# Performing addition inside the f-string
print(f"The sum of {a} and {b} is {a + b}.")
Output:
The sum of 10 and 5 is 15.
Explanation: The expression {a + b} is evaluated by Python before the string is displayed. Since a is 10 and b is 5, the expression produces 15.
Another Example:
# Python program to perform multiple calculations inside an f-string
a = 10
b = 5
# Performing calculations inside the f-string
print(f"Sum: {a + b}")
print(f"Difference: {a - b}")
print(f"Product: {a * b}")
Output
Sum: 15Difference: 5Product: 50
Explanation: Each expression inside {} is evaluated separately. This allows simple calculations to be performed directly while creating the output.
Formatting Numbers with F-Strings
F-strings are not only useful for inserting variables into strings. They also provide a convenient way to control how numbers are displayed. You can specify the number of decimal places, display percentages, add commas to large numbers, and more.
Formatting is especially useful when displaying prices, marks, measurements, percentages, financial data, or calculated results.
1. Formatting Decimal Places: You can control the number of decimal places displayed by using .f inside the curly braces.
Example:
# Python program to format a decimal number
price = 125.6789
# Displaying the price with two decimal places
print(f"Price: {price:.2f}")
Output:
Price: 125.68
Explanation:
- :.2f tells Python to display the number with 2 digits after the decimal point.
- The original value is 125.6789.
- Python rounds it to 125.68.
Another Example:
# Python program to display different decimal places
number = 45.67891
# Formatting the number to different decimal places
print(f"Two decimal places: {number:.2f}")
print(f"Three decimal places: {number:.3f}")
Output:
Two decimal places: 45.68Three decimal places: 45.679
2. Formatting Percentages: F-strings can also convert a decimal value into a percentage using the % formatting option.
Example
# Python program to format a decimal value as a percentage
percentage = 0.875
# Converting the decimal value into a percentage
print(f"Percentage: {percentage:.1%}")
Output
Percentage: 87.5%
Explanation: The value 0.875 represents 87.5%. The .1% format tells Python to multiply the value by 100 and display one decimal place followed by the % symbol.
3. Formatting Large Numbers with Commas: When working with large numbers, commas can make the output easier to read.
Example:
# Python program to format a large number with commas
population = 12500000
# Adding commas to the number
print(f"Population: {population:,}")
Output:
Population: 12,500,000
Explanation: The :, format adds commas between groups of three digits, making large numbers easier to read.
4. Formatting Strings with F-Strings: F-strings can also be used to control the appearance and alignment of text. This is useful when creating tables, reports, or organized output.
Example:
# Python program to align text using an f-string
name = "Rahul"
# Adding spaces to make the text occupy 10 characters
print(f"Name: {name:>10}")
Output:
Name: Rahul
Explanation: The :>10 formatting option aligns the text to the right within a space of 10 characters, you can also use < for left alignment and ^ for center. alignment.
5. Using F-Strings with Multiple Variables: An f-string can contain multiple variables at the same time. This is useful when several pieces of information need to be displayed in one message.
Example:
# Python program to display multiple variables using an f-string
name = "Aman"
age = 2
course = "Python"
# Displaying multiple variables in one string
print(f"Name: {name}, Age: {age}, Course: {course}")
Output:
Name: Aman, Age: 20, Course: Python
Explanation: The f-string contains three variables: name, age, and course. Python replaces each expression inside {} with its corresponding value.
6. F-Strings with Functions: You can also call functions inside the curly braces of an f-string. Python evaluates the function and inserts its returned value into the string.
Example:
# Python program to use a function inside an f-string
name = "python"
# Using the upper() function inside the f-string
print(f"Uppercase name: {name.upper()}")
Output:
Uppercase name: PYTHON
Explanation: The expression {name.upper()} calls the upper() method on the string stored in name. It converts "python" to "PYTHON" before displaying it.
7. F-Strings with Conditional Expressions: F-strings can contain simple conditional expressions. This allows the displayed text to change depending on a condition.
Example
# Python program to use a conditional expression inside an f-string
marks = 75
# Displaying the result based on marks
print(f"Result: {'Pass' if marks >= 40 else 'Fail'}")
Output:
Result: Pass
Explanation:
- The expression checks whether marks >= 40.
- If the condition is True, "Pass" is displayed.
- If the condition is False, "Fail" is displayed.
- Since the marks are 75, the output is "Pass".
8. Using F-Strings in Loops: F-strings are especially useful inside loops because they allow you to create dynamic output for every iteration.
Example:
# Python program to use f-strings inside a for loop
students = ["Rahul", "Aman", "Priya"]
# Displaying a message for each student
for student in students:
print(f"Welcome, {student}!")
Output:
Welcome, Rahul!Welcome, Aman!Welcome, Priya!
Explanation: During each iteration, the current student's name is inserted into the f-string. This creates a different message for every student.
9. F-Strings with Calculations and Formatting: You can combine expressions with number formatting in the same f-string.
Example:
# Python program to calculate and format a value using an f-string
price = 499.999
# Displaying the price with two decimal places
print(f"Product Price: ₹{price:.2f}")
Output:
Product Price: ₹500.00
Explanation: The expression is formatted using :.2f, which limits the displayed value to two decimal places. The ₹ symbol is ordinary text placed outside the curly braces.
Complete Program Using F-Strings
# Python program to demonstrate different uses of f-strings
name = "Rahul"
age = 18
marks = 87.456
course = "Python"
# Displaying basic information
print(f"Name: {name}")
print(f"Age: {age}")
print(f"Course: {course}")
# Formatting marks to two decimal places
print(f"Marks: {marks:.2f}")
# Performing a calculation inside an f-string
print(f"Next year age: {age + 1}")
# Using a conditional expression
print(f"Result: {'Pass' if marks >= 40 else 'Fail'}")
Output:
Name: RahulAge: 18Course: PythonMarks: 87.46Next year age: 19Result: Pass
Explanation of the Program
- name = "Rahul", age = 18, marks = 87.456, course = "Python": Four variables are created to store the student's name, age, marks, and course.
- print(f"Name: {name}"): The variable name is inserted directly into the f-string using {name}.
- print(f"Marks: {marks:.2f}"): The :.2f format specifier displays the marks with two digits after the decimal point. Therefore, 87.456 becomes 87.46.
- print(f"Next year age: {age + 1}"): The expression age + 1 is calculated inside the curly braces. Since the current age is 18, the result is 19.
- print(f"Result: {'Pass' if marks >= 40 else 'Fail'}"): A conditional expression checks whether the marks are at least 40. Since 87.456 >= 40, the result is "Pass".
Common Beginner Mistakes
1. Forgetting the f Before the String: The f tells Python to evaluate expressions inside {}. Without it, Python treats the curly braces as ordinary text.
Wrong:name = "Rahul"print("Hello, {name}")Output:Hello, {name}
Correct:name = "Rahul"print(f"Hello, {name}")Output:Hello, Rahul
2. Using Parentheses Instead of Curly Braces: F-strings use {} to insert variables and expressions. Parentheses do not tell an f-string to insert a variable. Expressions that should be evaluated must be placed inside curly braces {}.
Wrong:name = "Rahul"print(f"Hello, (name)")
Correct:name = "Rahul"print(f"Hello, {name}")
3. Forgetting That Expressions Go Inside Curly Braces: Calculations should be placed inside {} when they need to be evaluated.
Wrong:
a = 10b = 5print(f"Sum: a + b")Output:Sum: a + b
Correct:a = 10b = 5print(f"Sum: {a + b}")Output:Sum: 15
4. Using Incorrect Formatting Syntax: Formatting options must be written after a colon inside the curly braces.
Wrong:price = 125.6789print(f"Price: {price.2f}")
Correct:price = 125.6789print(f"Price: {price:.2f}")
5. Forgetting That Quotes Inside Expressions Can Conflict: When using strings inside an f-string expression, using the same type of quotation marks incorrectly can cause a syntax error.
Wrong:# Python program with conflicting quotation marksname = "Rahul"print(f"He said, "{name}"")
Correct:# Python program using different quotation marks correctlyname = "Rahul"print(f'He said, "{name}"')
Conclusion
F-strings provide a simple and readable way to create formatted strings in Python. By placing an f before a string and using curly braces {}, you can easily insert variables, perform calculations, call functions, and format values directly within the string.
They are particularly useful when creating dynamic messages, displaying calculations, formatting numerical data, and generating organized output. Once you understand variables, expressions, and basic formatting, f-strings become a convenient tool for writing cleaner and more readable Python programs.
Frequently Asked Questions (FAQs)
1. What are f-strings in Python?
F-strings are formatted string literals that allow variables and expressions to be inserted directly into a string using curly braces {}.
2. Why is the letter f used before a string?
The f tells Python that the string is a formatted string literal. It enables Python to evaluate expressions written inside {}.
3. Which version of Python introduced f-strings?
F-strings were introduced in Python 3.6.
4. Can I perform calculations inside an f-string?
Yes. Python can evaluate expressions inside {}.
5. Can f-strings format decimal numbers?
Yes. You can use format specifiers such as :.2f to control the number of decimal places.
0 Comments