F-strings

F-strings (formatted string literals) are a way to embed expressions inside string literals, using curly braces {}. They were introduced in Python 3.6 and provide a more readable and concise way to format strings compared to older methods like str.format() or the % operator.

F-strings allow you to directly include variables or expressions inside strings, making string interpolation simpler and faster.


Basic Syntax of F-strings

An f-string is prefixed with the letter f or F before the string. Expressions to be evaluated are enclosed in curly braces {}.

Syntax:

f"string {expression} more string"
  • Example:
    name = "Alice"
    age = 25
    greeting = f"Hello, {name}! You are {age} years old."
    print(greeting)  # Output: Hello, Alice! You are 25 years old.
    

Using Expressions Inside F-strings

F-strings can contain more than just simple variables. You can embed any valid Python expression inside the curly braces, and it will be evaluated at runtime. This includes arithmetic expressions, function calls, and other calculations.

  • Example:

    x = 10
    y = 5
    result = f"The sum of {x} and {y} is {x + y}."
    print(result)  # Output: The sum of 10 and 5 is 15.
    
  • Example with function call:

    def square(num):
        return num ** 2
    
    number = 4
    message = f"The square of {number} is {square(number)}."
    print(message)  # Output: The square of 4 is 16.
    

Formatting Numbers in F-strings

You can control the formatting of numbers (including integers, floats, and more) using format specifiers within the f-string.

Formatting Floats:

pi = 3.141592653589793
formatted = f"Pi to 2 decimal places: {pi:.2f}"
print(formatted)
# Output: Pi to 2 decimal places: 3.14
  • :.2f means the number will be formatted as a floating point number with 2 digits after the decimal point.

Padding and Alignment:

You can specify the width of the output and align the content within that width using format specifiers.

  • :<n>: Left-aligned, with a minimum width of n.
  • :>n: Right-aligned, with a minimum width of n.
  • :^n: Center-aligned, with a minimum width of n.
  • :0n: Pad with leading zeros, making the total width n.
number = 42
formatted_left = f"{number:<10}"  # Left-align, width 10
formatted_right = f"{number:>10}"  # Right-align, width 10
formatted_center = f"{number:^10}"  # Center-align, width 10
formatted_zero_pad = f"{number:010}"  # Pad with zeros, width 10

print(formatted_left)    # Output: '42        '
print(formatted_right)   # Output: '        42'
print(formatted_center)  # Output: '    42    '
print(formatted_zero_pad)  # Output: '0000000042'

Specifying Number of Decimal Places

In addition to using :.2f for floating-point precision, you can format other numeric types similarly, specifying the width, padding, and alignment.

value = 123.456789
formatted = f"Value rounded to 3 decimal places: {value:.3f}"
print(formatted)
# Output: Value rounded to 3 decimal places: 123.457

Formatting Dates with F-strings

You can format datetime objects using strftime style format codes inside the f-string.

Example with Date:

from datetime import datetime

now = datetime.now()
formatted = f"Current date and time: {now:%Y-%m-%d %H:%M:%S}"
print(formatted)
# Output: Current date and time: 2024-12-26 10:30:45

Here, %Y-%m-%d %H:%M:%S is the format code:

  • %Y: 4-digit year
  • %m: 2-digit month
  • %d: 2-digit day
  • %H: 2-digit hour (24-hour clock)
  • %M: 2-digit minute
  • %S: 2-digit second

Nested F-strings

You can have f-strings inside f-strings, though it is usually not very common. It can be useful in some cases.

name = "Bob"
greeting = f"Hello, {f'Nice to meet you, {name}!'}"
print(greeting)
# Output: Hello, Nice to meet you, Bob!

Escape Curly Braces in F-strings

If you need to include literal curly braces { or } inside an f-string (for example, if you're generating JSON or working with regular expressions), you need to escape them by doubling them {{ or }}.

formatted = f"{{This is a literal curly brace}}"
print(formatted)
# Output: {This is a literal curly brace}

Using F-strings for Dictionary Values

You can use f-strings to directly format values from dictionaries by accessing the values with the key.

  • Example:
    person = {"name": "Alice", "age": 25}
    greeting = f"{person['name']} is {person['age']} years old."
    print(greeting)  # Output: Alice is 25 years old.
    

F-strings with Expressions and Functions

You can use f-strings for more complex expressions and function calls within the string.

Example:

x = 10
message = f"The result of {x} * 2 is {x * 2}."
print(message)  # Output: The result of 10 * 2 is 20.

You can use conditional expressions (also known as ternary operators) inside f-strings.

Example (Using a conditional expression inside f-string):

is_active = True
status = f"User is {'active' if is_active else 'inactive'}."
print(status)  # Output: User is active.
age = 25
formatted = f"You are {'adult' if age >= 18 else 'minor'}."
print(formatted)
# Output: You are adult.

Using !r (Repr) in F-strings

If you want to include the repr() (representation) of an object in the string, you can use !r. This is especially useful for debugging, as it shows the "official" string representation of the object.

name = "Alice"
formatted = f"Name with repr: {name!r}"
print(formatted)
# Output: Name with repr: 'Alice'

The !r calls the repr() function on the variable, which for strings adds quotes around the value.


Performance Benefits of F-strings

F-strings are faster than older string formatting methods like str.format() and % formatting because they are evaluated at runtime and do not require method calls. This makes them ideal for performance-critical applications.


Summary of F-string Formatting Syntax:

  • Basic F-string: f"Hello {name}"
  • Precision Formatting: f"Pi: {pi:.2f}"
  • Alignment and Width: f"{value:<10}", f"{value:^10}", f"{value:>10}", f"{value:010}"
  • Date Formatting: f"{datetime:%Y-%m-%d %H:%M:%S}"
  • Nested F-strings: f"Hello, {f'Nice to meet you, {name}!'}"
  • Escape Curly Braces: f"{{this is a literal brace}}"
  • Using Dictionary Keys: f"{person['name']}"
  • Conditional Expressions: f"{'adult' if age >= 18 else 'minor'}"
  • !r (repr) for Object Representation: f"{name!r}"

Task

Practice: F-strings in Python

Objective: Practice creating f-strings with different expressions and formatting options to format and display values effectively.

  1. Basic F-string Usage:

    • Write a program that takes the user's name and age as input and prints a greeting using an f-string.
    name = input("Enter your name: ")
    age = int(input("Enter your age: "))
    print(f"Hello, {name}! You are {age} years old.")
    
  2. Formatting Numbers:

    • Create an f-string that formats a floating-point number to two decimal places and prints it.
    number = 3.14159
    print(f"Formatted number: {number:.2f}")  # Output: Formatted number: 3.14
    
    • Use an f-string to format an integer to always show 4 digits, padding with leading zeros.
    integer = 42
    print(f"Formatted integer: {integer:04d}")  # Output: Formatted integer: 0042
    
  3. Using Functions Inside F-strings:

    • Write a program that uses an f-string to display the result of a function call (e.g., square of a number).
    def square(num):
        return num ** 2
    
    number = 5
    print(f"The square of {number} is {square(number)}")
    
  4. Dictionary Values with F-strings:

    • Create a dictionary with information about a person (name, age, city) and use an f-string to print out this information.
    person = {"name": "Alice", "age": 30, "city": "New York"}
    print(f"{person['name']} is {person['age']} years old and lives in {person['city']}.")
    
  5. Complex Expressions:

    • Write a program that calculates the sum of two numbers and displays the result inside an f-string. Use a conditional expression to print a message based on whether the sum is greater than 10.
    num1 = 7
    num2 = 5
    sum_result = num1 + num2
    print(f"The sum of {num1} and {num2} is {sum_result}. {'The sum is greater than 10.' if sum_result > 10 else 'The sum is less than or equal to 10.'}")
    

Copyright © 2025 Devship. All rights reserved.

Made by imParth