F-strings, also known as “formatted string literals”, were introduced in Python 3.6 as a way to simplify string formatting. F-strings allow you to embed expressions inside string literals, using curly braces {}
to enclose the expressions. These expressions are evaluated at runtime and formatted using the format specification language, which is similar to the format strings used with the str.format()
method. F-strings provide a concise and readable way to embed variables and expressions within strings.
You can implement f-strings in Python using many ways, for example, by using string interpolation, mathematical operations, date formatting, and number formatting. In this article, I will explain the f-strings by using all these functions with examples.
1. Quick Examples of F-strings
If you are in a hurry, below are some quick examples of f-strings.
# Quick examples of f-strings
from datetime import datetime
# Example 1: Variable using f-strings
variable = 20
formatted_string = f"The value of the variable is {variable}"
# Example 2: Variable names using f-strings
language = "Python"
tutorial = "SparkByExamples"
formatted_string = f"I'm learning {language} from {tutorial}."
# Example 3: Mathematical operations using f-strings
# Multiplication
num1 = 35
num2 = 6
formatted_string = f"The product of {num1} and {num2} is {num1 * num2}"
# Example 4: F-strings using addition
num1 = 35
num2 = 6
formatted_string = f"The sum of {num1} and {num2} is {num1 + num2}"
# Example 5: Formatting the date using f-strings
current_date_time = datetime.now()
formatted_date = f"Formatted Date: {current_date_time:%Y-%m-%d}"
# Example 6: Formatting both date and time
formatted_datetime = f"Formatted Date and Time: {current_date_time:%Y-%m-%d %H:%M:%S}"
# Example 7: Format with a specific number of decimal places
pi = 3.141592653589793
formatted_pi = f"Formatted Pi: {pi:.2f}"
# Example 8: Format hexadecimal
number = 27
formatted_hexadecimal = f"Hexadecimal: {number:x}"
# Example 9: Syntax error in f-string
name = "Alice"
age = 12
formatted_string = f"My name is {name and I am {age} years old."
2. String Interpolation Using F-strings
F-strings in Python allow for easy string interpolation, where expressions inside curly braces {}
are evaluated and replaced with their values in the resulting string. This makes it convenient to construct strings with embedded variables or expressions.
You can define a variable variable
with a value of 20 and then use an f-string to create a formatted string where the value of the variable is embedded within the string.
# Defining variable
variable = 20
# Variable using f-strings
formatted_string = f"The value of the variable is {variable}"
print(formatted_string)
Yields below output.
![python f-strings](https://i0.wp.com/sparkbyexamples.com/wp-content/uploads/2023/10/image-49.png?resize=294%2C32&ssl=1)
It defines two variables, language
and tutorial
, and then uses an f-string to create a formatted string where the values of these variables are included. F-strings are a concise and convenient way to embed expressions inside string literals in Python.
In the below example, the variables language
and tutorial
are included directly within the f-string, allowing you to create a formatted string with the values of these variables.
# Defining variables
language = "Python"
tutorial = "SparkByExamples"
# Variable names using f-strings
formatted_string = f"I'm learning {language} from {tutorial}."
print(formatted_string)
Yields below output.
![python f-strings](https://i0.wp.com/sparkbyexamples.com/wp-content/uploads/2023/10/image-50.png?resize=376%2C35&ssl=1)
3. Mathematical Operations Using F-strings
You can define two variables num1
and num2
, multiply them, and then use an f-string to create a formatted string where the product of the two numbers is included.
# Defining variables
num1 = 35
num2 = 6
# Mathematical operations using f-strings
# Multiplication
formatted_string = f"The product of {num1} and {num2} is {num1 * num2}"
print(formatted_string)
# Output:
# The product of 35 and 6 is 210
To define two variables num1
and num2
, add them, and then use an f-string to create a formatted string where the sum of the two numbers is included.
# Defining variables
num1 = 35
num2 = 6
# F-strings using addition
formatted_string = f"The sum of {num1} and {num2} is {num1 + num2}"
print(formatted_string)
# Output:
# The sum of 35 and 6 is 41
4. Date Formatting Using F-strings
You can format dates using f-strings in Python. You can use the strftime
method from the datetime
module to format dates and times as strings according to a specified format.
In the below example, It imports the datetime
class from the datetime
module, gets the current date and time using datetime.now()
, and then uses an f-string to format the date as a string in the format YYYY-MM-DD
. When you run this code, it will output the current date in the specified format.
from datetime import datetime
# Formatting the date using f-strings
current_date_time = datetime.now()
formatted_date = f"Formatted Date: {current_date_time:%Y-%m-%d}"
print(formatted_date)
# Output
# Formatted Date: 2023-10-12
# Formatting both date and time
formatted_datetime = f"Formatted Date and Time: {current_date_time:%Y-%m-%d %H:%M:%S}"
print(formatted_datetime)
# Output
# Formatted Date and Time: 2023-10-12 10:17:05
5. Number Formatting Using F-strings
You can format numbers using f-strings in Python. You can specify the format within the curly braces of an f-string to control how numbers are displayed.
In the first example, It defines a floating-point number pi
, and uses an f-string to format it with two decimal places. The :.2f
inside of the curly braces {}
specifies that the floating-point number pi
should be formatted with two decimal places. The second example :10.4f
specifies a width of 10 characters and 4 decimal places for the floating-point number.
# Define a floating-point number
pi = 3.141592653589793
# Format with a specific number of decimal places
formatted_pi = f"Formatted Pi: {pi:.2f}"
print(formatted_pi)
# Output:
# Formatted Pi: 3.14
# Format with a specific width and precision
formatted_number = f"Formatted Number: {pi:10.4f}"
print(formatted_number)
# Output
# Formatted Number: 3.1416
Similarly, you can define an integer number
and use an f-string to format it as a hexadecimal number. In this case, :x
the curly braces {}
specify that the integer number
should be formatted as a hexadecimal number
# Define an integer
number = 27
# Format hexadecimal
formatted_hexadecimal = f"Hexadecimal: {number:x}"
print(formatted_hexadecimal)
# Output:
# Hexadecimal: 1b
6. Demonstrating Syntax Error
Let’s demonstrate a syntax error involving f-strings. For instance, there is a syntax error in the f-string. The curly braces are not properly closed, causing a syntax error. When you try to run this code, you will get a SyntaxError
similar to the following.
# Defining variables
name = "Alice"
age = 12
# Syntax error in f-string
formatted_string = f"My name is {name and I am {age} years old."
print(formatted_string)
# Output:
# SyntaxError: f-string: expecting '}'
Conclusion
In this article, I have explained f-strings in Python by using string interpolation, mathematical operations, date formatting, and number formatting with examples.
Happy Learning !!
Related Articles
- Python String Split Including Spaces
- Python Set Methods
- Check if a String is a Float in Python
- Python Capitalize First Letter of String
- How to Convert Dictionary to String Python?
- Python Set remove() – Remove Element
- Python Remove Item from Set
- Python Set pop() method
- Python Count Specific Character in String
- Python Convert String to Float
- Python Count Characters in String