← Back to Blog
    TutorialFebruary 24, 20246 min read

    Python f-strings: The Complete Guide to String Formatting

    Master Python f-strings with clear examples. Learn number formatting, alignment, expressions, and debugging tricks to write cleaner string output.

    Python f-strings Explained

    Formatted string literals, known as f-strings, are the cleanest way to build strings in modern Python. They are faster than older methods and far easier to read. This guide walks through every feature you need.

    What Is an f-string

    An f-string is a string with the letter f before the opening quote. Any value inside curly braces gets inserted directly into the text.

    name = "Ada"
    age = 36
    print(f"{name} is {age} years old")

    Using Expressions Inside Braces

    You can place any valid Python expression inside the braces, not just variable names. Python evaluates it and drops the result into the string.

    a, b = 6, 4
    print(f"The sum is {a + b}")
    print(f"Upper: {'hello'.upper()}")

    Formatting Numbers

    f-strings shine when you need controlled number output. A format specifier after a colon sets decimals, padding, and more.

    pi = 3.14159
    print(f"Rounded: {pi:.2f}")
    print(f"Percent: {0.25:.0%}")

    Aligning Text

    You can align values inside a fixed width, which is perfect for tidy tables. Use the less than, greater than, and caret symbols for left, right, and center.

    for item in ["apple", "fig", "kiwi"]:
        print(f"{item:<8}|")

    Adding Thousands Separators

    Large numbers become readable with a comma format. This works for both integers and floats.

    population = 1500000
    print(f"{population:,}")

    The Debugging Trick

    Adding an equals sign inside the braces prints both the expression and its value. This saves time when checking variables.

    score = 95
    print(f"{score=}")

    Why f-strings Beat Older Methods

    The percent operator and the format method still work, but f-strings keep the value next to the text where it belongs. That closeness makes code easier to scan and harder to break. Once you switch, you rarely go back.

    Practice Now

    Open the playground and try formatting a price, a percentage, and an aligned column. A few minutes of hands on practice will make f-strings feel natural in your everyday code.

    By PythonExecutor Team

    Related Articles