• Home
  • 4.17 f-Strings – Part 1

4.17 f-Strings – Part 1

View Categories

4.17 f-Strings – Part 1

4 min read

An f-string (formatted string literal) is the modern and recommended way to format strings in Python.

An f-string is created by placing the letter f or F immediately before the opening quotation mark. Expressions enclosed within curly braces ({}) are evaluated and their values are inserted directly into the string.

Compared to % formatting and the format() method, f-strings are easier to read, require less code, and generally execute faster.

F-strings are widely used in modern Python programs for displaying variables, calculations, and expressions.


Syntax #

f"Text {expression}"

or

F"Text {expression}"

Components #

Component Description
f or F Prefix indicating a formatted string literal.
{} Placeholder containing a variable or expression.
expression Variable, value, or expression evaluated by Python.

Example 1: Formatting a Variable #

main.py

name = "Alice"

print(f"Hello, {name}!")

Output #

Hello, Alice!

Explanation #

  • The f prefix creates an f-string.
  • {name} is replaced by the value of the variable name.
  • The formatted string is printed.

Example 2: Formatting Multiple Variables #

main.py

name = "John"
age = 25

print(f"Name: {name}, Age: {age}")

Output #

Name: John, Age: 25

Explanation #

  • Both variables are placed inside curly braces.
  • Python replaces each placeholder with its corresponding value.
  • The resulting string is displayed.

Example 3: Using Expressions #

main.py

a = 10
b = 20

print(f"Sum = {a + b}")

Output #

Sum = 30

Explanation #

  • The expression a + b is evaluated.
  • Python inserts the result into the string.
  • Expressions can be written directly inside {}.

Example 4: Performing Calculations #

main.py

length = 5
width = 8

print(f"Area = {length * width}")

Output #

Area = 40

Explanation #

  • The multiplication expression is evaluated.
  • The computed result replaces the placeholder.
  • No separate variable is required.

Example 5: User Input #

main.py

name = input("Enter your name: ")

print(f"Welcome, {name}!")

Sample Input #

Alice

Output #

Welcome, Alice!

Explanation #

  • The user enters a name.
  • The value stored in name is inserted into the f-string.
  • The greeting is displayed.

Example 6: Mixing Different Data Types #

main.py

product = "Laptop"
quantity = 3
price = 599.99

print(f"Product: {product}, Quantity: {quantity}, Price: ${price}")

Output #

Product: Laptop, Quantity: 3, Price: $599.99

Explanation #

  • Strings, integers, and floating-point numbers can all be inserted.
  • Python automatically converts values to string form when necessary.
  • The output is easy to read.

Example 7: Calling Functions Inside an f-String #

main.py

word = "python"

print(f"{word.upper()}")

Output #

PYTHON

Explanation #

  • Function calls can be placed inside {}.
  • upper() converts the string to uppercase.
  • The returned value is inserted into the string.

Example 8: Using an Uppercase Prefix #

main.py

language = "Python"

print(F"Learning {language}")

Output #

Learning Python

Explanation #

  • Both f and F create formatted string literals.
  • They behave exactly the same.
  • The choice is based on coding style.

Example 9: Formatting a Boolean Expression #

main.py

age = 18

print(f"Eligible: {age >= 18}")

Output #

Eligible: True

Explanation #

  • The comparison age >= 18 is evaluated.
  • The Boolean result is inserted into the string.
  • Expressions inside {} can return any data type.

Example 10: Checking the Result Type #

main.py

name = "Python"

result = f"Welcome {name}"

print(result)
print(type(result))

Output #

Welcome Python
<class 'str'>

Explanation #

  • An f-string creates a new string.
  • The formatted result is stored in result.
  • Its data type is str.

Common Mistakes #

1. Forgetting the f Prefix #

Incorrect

name = "Alice"

print("Hello, {name}")

Output #

Hello, {name}

Reason

Without the f prefix, Python treats {name} as ordinary text.

Correct

print(f"Hello, {name}")

2. Using Undefined Variables #

Incorrect

print(f"Hello, {username}")

Output #

NameError: name 'username' is not defined

Reason

The variable inside {} must already exist.

Correct

username = "Alice"

print(f"Hello, {username}")

3. Forgetting the Curly Braces #

Incorrect

name = "Alice"

print(f"Hello, name")

Output #

Hello, name

Reason

Variables must be enclosed within {}.

Correct

print(f"Hello, {name}")

4. Assuming an f-String Changes the Variable #

Incorrect

name = "Alice"

f"Hello, {name}"

print(name)

Output #

Alice

Reason

An f-string creates a new string.
It does not modify the original variable.


Best Practices #

  • Prefer f-strings over % formatting and format() in modern Python programs.
  • Use meaningful variable names inside f-strings.
  • Keep expressions simple for better readability.
  • Use f-strings for messages, reports, and user-friendly output.
  • Remember to include the f prefix before the opening quotation mark.

Key Points to Remember #

  • An f-string is created using the f or F prefix.
  • Values inside {} are evaluated automatically.
  • Variables, expressions, and function calls can be placed inside {}.
  • F-strings produce a new string of type str.
  • F-strings are more readable than % formatting and format().
  • The f prefix is mandatory.
  • F-strings are the recommended formatting method in modern Python.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *