0% found this document useful (0 votes)
6 views4 pages

Python f-strings: A Comprehensive Guide

f-strings, introduced in Python 3.6, allow for embedding expressions inside string literals using curly braces, enhancing readability and efficiency in string formatting. They can include variables, expressions, and even format numbers and dates directly within the string. Overall, f-strings provide a clear and concise way to create dynamic strings in Python.

Uploaded by

aaron.butt16
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views4 pages

Python f-strings: A Comprehensive Guide

f-strings, introduced in Python 3.6, allow for embedding expressions inside string literals using curly braces, enhancing readability and efficiency in string formatting. They can include variables, expressions, and even format numbers and dates directly within the string. Overall, f-strings provide a clear and concise way to create dynamic strings in Python.

Uploaded by

aaron.butt16
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Using `print(f)` in Python

In Python, the `print(f)` or f-string formatting is a way to embed expressions


inside string literals using curly braces `{}`. This method, introduced in Python
3.6, is a convenient and highly readable way to format strings by including
variable values or expressions directly in the string.
What is an f-string?
An f-string is a string prefixed with the letter `f` or `F` before the opening
quotation mark. Inside the f-string, any valid Python expression inside curly
braces `{}` will be evaluated, and its result will be formatted into the string.

print(f"Your text {expression}")


- The `f` before the string signals to Python that it's an f-string.
- The expressions inside `{}` will be replaced by their values when the string is
printed.

Example 1: Basic f-string with Variables


name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.")

Explanation:
- `name` and `age` are variables.
- Inside the f-string, `{name}` and `{age}` are placeholders for the variable
values.
- The output will be:

My name is Alice and I am 30 years old.

Example 2: Using Expressions in f-strings

You can also include expressions inside `{}` that Python will evaluate and
include in the string.

a=5
b=3

Page 1 of 4
print(f"The sum of {a} and {b} is {a + b}.")

Explanation:
- The expression `{a + b}` is evaluated to `8` and inserted into the string.
- The output will be:
The sum of 5 and 3 is 8.

Example 3: Formatting Numbers in f-strings


You can format numbers with f-strings using a colon `:` inside the curly braces.
This is useful for controlling how numbers are displayed (e.g., number of decimal
places, alignment, etc.).

# Formatting Floating-Point Numbers

pi = 3.141592653589793
print(f"Pi rounded to two decimal places is {pi:.2f}.")

Explanation:
- `{pi:.2f}` tells Python to format the `pi` variable to 2 decimal places.
- The output will be:
Pi rounded to two decimal places is 3.14.

Formatting Integers with Leading Zeros


number = 42
print(f"The number with leading zeros is {number:05d}.")

Explanation:
- `{number:05d}` tells Python to format the number with a total width of 5
characters, filling with leading zeros (`0`) if necessary.
- The output will be:
The number with leading zeros is 00042.

Page 2 of 4
Example 4: Using f-strings for Date and Time

If you're working with dates, you can format them easily using f-strings.

from datetime import datetime


current_time = [Link]()
print(f"The current date and time is {current_time:%Y-%m-%d %H:%M:%S}.")

Explanation:
- The format specifier `%Y-%m-%d %H:%M:%S` formats the `current_time` as
`year-month-day hours:minutes:seconds`.
- The output will be something like:

The current date and time is 2024-10-21 14:30:45.

Example 7: Multiline f-strings

f-strings can also span multiple lines.

name = "Jane"
age = 28
city = "New York"

print(f"""
Hello, my name is {name}.
I am {age} years old.
I live in {city}.
""")
Explanation:
- The f-string spans multiple lines, and each line correctly replaces the variables
inside `{}`.

Page 3 of 4
- The output will be:

Hello, my name is Jane.


I am 28 years old.
I live in New York.

Advantages of f-strings

1. Readability : f-strings are clear and concise, making your code more
readable.
2. Efficiency : f-strings are faster compared to older string formatting methods
like `%` formatting or `.format()`.
3. Flexibility : You can use variables, expressions, functions, and even format
numbers directly inside f-strings.

Page 4 of 4

You might also like