Built with Tutify.io

    AIStudyLabs

    Advanced String Formatting: f-strings and format()

    Advanced String Formatting: f-strings and format()

    Introduction

    In this lesson, we delve into advanced string formatting in Python, focusing on f-strings and the str.format() method. Building on your existing string manipulation skills, you will learn how to craft highly formatted text using inline interpolation, number formatting, and how to choose the appropriate tool for various scenarios involving dynamic message generation.

    Using f-strings for String Interpolation

    F-strings, introduced in Python 3.6, offer a concise and readable way to embed expressions and variables directly in a string. The syntax involves prefixing a string with f or F and embedding expressions within curly braces {}.

    name = "Alice"
    age = 28
    formatted_string = f"Hello, my name is {name} and I am {age} years old."
    print(formatted_string)
    
    # Output
    Hello, my name is Alice and I am 28 years old.
    

    Inline Expression Evaluation

    F-strings allow for executing expressions on-the-fly, providing great flexibility.

    x = 10
    y = 20
    calculation = f"{x} multiplied by {y} equals {x * y}."
    print(calculation)
    
    # Output
    10 multiplied by 20 equals 200.
    

    Formatting Numbers with Precision, Width, and Alignment

    Both f-strings and str.format() facilitate the formatting of numbers, allowing for precision control, width specification, alignment, and use of digits' separators.

    Precision and Width

    value = 123.4567
    formatted_value = f"{value:.2f}"
    print(formatted_value)
    
    # Output
    123.46
    

    Alignment and Fill

    value = 42
    formatted_value = f"|{value:<10}|{value:^10}|{value:>10}|"
    print(formatted_value)
    
    # Output
    |42        |    42    |        42|
    

    Thousands Separator

    number = 1000000
    formatted_number = f"{number:,}"
    print(formatted_number)
    
    # Output
    1,000,000
    

    Advanced Date and Custom Object Formatting

    F-strings can also seamlessly format dates and custom objects by leveraging class methods.

    Date Formatting

    from datetime import datetime
    now = datetime.now()
    formatted_date = f"Today's date is {now:%B %d, %Y}."
    print(formatted_date)
    
    # Output
    Today's date is October 29, 2023.
    

    Custom Object Representation

    For custom objects, implementing the __format__ method allows you to control how they appear in formatted strings.

    class Car:
        def __init__(self, make, model):
            self.make = make
            self.model = model
        def __format__(self, format_spec):
            return f"{self.make} - {self.model}"
    
    car = Car("Toyota", "Corolla")
    print(f"Car: {car}")
    
    # Output
    Car: Toyota - Corolla
    

    Comparing f-strings and str.format()

    Choosing the Right Approach

    Dynamic Message Construction

    Combining text, variables, and formatting options allows for the creation of dynamic and well-structured output.

    items = ["apples", "bananas", "cherries"]
    formatted_list = ", ".join(f"{index+1}. {item}" for index, item in enumerate(items))
    message = f"Shopping list: {formatted_list}."
    print(message)
    
    # Output
    Shopping list: 1. apples, 2. bananas, 3. cherries.
    

    Summary / Key Takeaways

    In this lesson, Advanced String Formatting: f-strings and format(), you have learned:

    Python Programming – Complete Course with Practical Examples — Working with Strings in Depth

    Getting Started with Python and the Course

    Python Syntax, Indentation, and Core Concepts

    Variables, Data Types, and Type Conversion

    Operators, Expressions, and Control Flow

    Loops and Iteration Patterns

    Working with Strings in Depth

    Collections: Lists, Tuples, Sets, and Dictionaries

    Functions and Program Structuring

    Functional Programming Concepts in Python

    Modules, Packages, and Code Organization

    Error Handling and Debugging Fundamentals

    File Handling and Data Formats

    Object-Oriented Programming in Python

    Advanced Python: Iterators, Generators, and Decorators

    Python Standard Library for Real-World Tasks

    Python for Automation and Scripting

    Testing and Quality Assurance in Python

    Tutorial Not Found