Python Basics

Course by zooboole,

Last Updated on 2025-02-26 16:14:49

F-strings

Formatting strings efficiently is crucial when dealing with dynamic content. Python provides multiple ways to format strings, and one of the most modern and convenient methods is using f-strings. Introduced in Python 3.6, f-strings provide a readable and concise way to embed expressions inside string literals

Understanding F-strings

F-strings, or formatted string literals, are prefixed with an f or F before the opening quotation mark. They allow us to insert variables and expressions directly inside curly braces {} within a string.

Syntax of F-strings

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

Output

My name is Alice and I am 25 years old.

Why Use F-strings?

F-strings provide several advantages:

Readability: They are more concise and easier to understand than traditional formatting methods.

Performance: Faster than .format() and % formatting.

Flexibility: Can include expressions directly.

Using Expressions Inside F-strings

F-strings allow evaluating expressions inside placeholders:

x = 5
y = 3
print(f"The sum of {x} and {y} is {x + y}.")

Output

The sum of 5 and 3 is 8.

Formatting Numbers with F-strings

You can also control number formatting:

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

Output

Pi rounded to 2 decimal places: 3.14

Padding and Alignment

F-strings allow controlling text alignment:

name = "Bob"
print(f"|{name:10}|")  # Right align
print(f"|{name:^10}|")  # Center align

Output

|Bob       |
|       Bob|
|   Bob    |

Using F-strings with Dictionaries

person = {"name": "Eve", "age": 30}
print(f"{person['name']} is {person['age']} years old.")

Output

Eve is 30 years old.

Exercise: Try It Yourself!

  1. Create a program that takes a user's name and favorite color and prints: "Hello [name], your favorite color is [color]!"

  2. Write a program that takes two numbers as input and prints their sum, difference, and product using f-strings.

Example solution

# User input
title = "Python Learner"
score = 95
print(f"Congratulations! {title}, you scored {score}% on the test!")

F-strings make working with dynamic text easy and efficient. In the next lesson, we will explore more advanced string manipulation techniques!