Python Tutorial

Python Variable

Python Operators

Python Sequence

Python String

Python Flow Control

Python Functions

Python Class and Object

Python Class Members (properties and methods)

Python Exception Handling

Python Modules

Python File Operations (I/O)

Python format string

In this tutorial, we'll learn about format strings in Python, which are a more concise way to create formatted strings by using f-strings (formatted string literals). Introduced in Python 3.6, f-strings allow you to embed expressions inside string literals, using curly braces {}. F-strings are a powerful and efficient way to format strings in comparison to using the str.format() method or string concatenation.

Example 1: Basic usage of f-strings

name = "John"
age = 25

text = f"My name is {name} and I am {age} years old."
print(text)  # Output: My name is John and I am 25 years old.

Example 2: Embedding expressions in f-strings

You can include any Python expressions inside the curly braces, such as mathematical operations or function calls.

a = 5
b = 3

result = f"{a} times {b} is {a * b}."
print(result)  # Output: 5 times 3 is 15.
def greet(name):
    return f"Hello, {name}!"

name = "Alice"
message = greet(name)
print(message)  # Output: Hello, Alice!

Example 3: Formatting options

You can include formatting options inside the curly braces to control the presentation of the value. For example, you can set the number of decimal places for a floating-point number or control the alignment of the value in a fixed-width field.

pi = 3.14159265
formatted_pi = f"{pi:.2f}"
print(formatted_pi)  # Output: 3.14

name = "John"
formatted_name = f"{name:<10}"  # Left-align in a 10-character field
print(formatted_name)  # Output: John      

Example 4: Using f-strings with dictionaries

You can use f-strings to access dictionary values by providing the key inside the curly braces.

person = {"name": "John", "age": 25}
text = f"My name is {person['name']} and I am {person['age']} years old."
print(text)  # Output: My name is John and I am 25 years old.

In summary, f-strings (formatted string literals) allow you to create formatted strings in a concise and efficient way by embedding expressions inside string literals using curly braces. You can include any Python expressions and formatting options inside the braces to control the presentation of the values. F-strings are a powerful and modern way to create formatted strings in Python.

  1. How to Use Format Strings in Python:

    • Format strings allow the inclusion of expressions, variables, and literals using curly braces {} as placeholders.
    # Example
    name = "Alice"
    age = 25
    formatted_string = "My name is {} and I am {} years old.".format(name, age)
    
  2. String Formatting with f-strings in Python:

    • f-strings provide a concise way to format strings by embedding expressions directly within curly braces.
    # Example
    name = "Bob"
    age = 30
    formatted_string = f"My name is {name} and I am {age} years old."
    
  3. Creating Formatted Strings with format() in Python:

    • The format() method is used for creating formatted strings with placeholders.
    # Example
    item = "book"
    price = 20.50
    invoice = "Item: {}, Price: ${:.2f}".format(item, price)
    
  4. String Interpolation and Placeholders in Python:

    • Format strings support placeholders that are replaced with corresponding values during string creation.
    # Example
    fruit = "apple"
    quantity = 3
    order_summary = "Ordered {} {}s".format(quantity, fruit)
    
  5. Advanced Formatting Options in Python Format Strings:

    • Format strings offer advanced options like alignment, width, precision, and more.
    # Example
    pi_value = 3.14159
    formatted_pi = "Formatted Pi: {:^10.2f}".format(pi_value)
    
  6. Formatting Variables and Expressions in Python Strings:

    • Include variables and expressions directly within format strings.
    # Example
    x = 10
    y = 20
    result = "Result: {} + {} = {}".format(x, y, x + y)
    
  7. String Alignment and Width in Python Format Strings:

    • Control the alignment and width of formatted output using format().
    # Example
    city = "Paris"
    formatted_city = "City: {:>10}".format(city)
    
  8. Format Specification Language in Python:

    • The format specification language allows detailed control over formatting.
    # Example
    value = 12345.6789
    formatted_value = "Formatted: {:,.2f}".format(value)
    
  9. Using Format Strings for Dynamic Output in Python:

    • Format strings dynamically based on variables and expressions.
    # Example
    dynamic_variable = "name"
    dynamic_value = "John"
    dynamic_output = "{}: {}".format(dynamic_variable.capitalize(), dynamic_value)