Python Tutorial

Python Flow Control

Python Functions

Python Data Types

Python Date and Time

Python Files

Python String

Python List

Python Dictionary

Python Variable

Python Input/Output

Python Exceptions

Python Advanced

Formatting Output in Python

In Python, there are several ways to format output for better readability and presentation. This tutorial covers the most commonly used methods: string concatenation, the %-formatting, the str.format() method, and f-strings (formatted string literals).

  • String Concatenation You can use the + operator to concatenate strings. However, this method can be inefficient and less readable when dealing with multiple variables or complex expressions.

Example:

name = "Alice"
age = 30

print("My name is " + name + " and I am " + str(age) + " years old.")
  • %-formatting The %-formatting method uses placeholders in the string and the % operator to substitute variables. This method is similar to the one used in C's printf. However, it's considered somewhat outdated in modern Python.

Example:

name = "Alice"
age = 30

print("My name is %s and I am %d years old." % (name, age))
  • str.format() The str.format() method uses curly braces {} as placeholders and the format() function to substitute variables. It's more versatile and easier to read than %-formatting.

Example:

name = "Alice"
age = 30

print("My name is {} and I am {} years old.".format(name, age))

You can also use positional and keyword arguments to improve readability:

print("My name is {0} and I am {1} years old. {0} is a programmer.".format(name, age))
print("My name is {name} and I am {age} years old.".format(name="Alice", age=30))
  • f-strings (Formatted String Literals) Introduced in Python 3.6, f-strings provide a more concise and readable way to format strings. To use f-strings, prefix the string with an f or F and include expressions inside curly braces {}.

Example:

name = "Alice"
age = 30

print(f"My name is {name} and I am {age} years old.")

F-strings also support various formatting options, such as:

  • Width and alignment: f"{variable:<10}" (left-align), f"{variable:>10}" (right-align), f"{variable:^10}" (center-align)
  • Number of decimal places: f"{variable:.2f}"
  • Formatting integers: f"{variable:04d}" (padding with zeros)

Example:

pi = 3.1415926535
number = 42

print(f"Pi rounded to 2 decimal places: {pi:.2f}")
print(f"Number padded with zeros: {number:04d}")

In summary, f-strings are the preferred method for formatting output in modern Python due to their readability, simplicity, and performance. However, it's essential to be familiar with other methods to work with older code or when using older versions of Python.

  1. String formatting in Python:

    • Description: String formatting allows you to create formatted strings by combining variables and constants.
    • Example Code:
      name = "Alice"
      age = 25
      formatted_string = "My name is {} and I am {} years old.".format(name, age)
      print(formatted_string)
      
  2. Using f-strings for output formatting in Python:

    • Description: f-strings provide a concise way to embed expressions inside string literals.
    • Example Code:
      name = "Bob"
      age = 30
      formatted_string = f"My name is {name} and I am {age} years old."
      print(formatted_string)
      
  3. Formatting numbers in Python output:

    • Description: Format numbers for output with precision and control over decimal places.
    • Example Code:
      pi_value = 3.14159
      formatted_number = "Value of pi: {:.2f}".format(pi_value)
      print(formatted_number)
      
  4. Aligning text and numbers in Python output:

    • Description: Control alignment of text and numbers within a formatted string.
    • Example Code:
      product = "Apple"
      price = 2.5
      formatted_output = "{:<10} : {:.2f}".format(product, price)
      print(formatted_output)
      
  5. Formatting dates and times in Python:

    • Description: Use the strftime method to format dates and times.
    • Example Code:
      from datetime import datetime
      
      current_date = datetime.now()
      formatted_date = current_date.strftime("%Y-%m-%d %H:%M:%S")
      print(formatted_date)
      
  6. Padding and spacing in Python output:

    • Description: Add padding and spacing to align text and numbers in a formatted string.
    • Example Code:
      product = "Banana"
      quantity = 15
      formatted_output = "{:10} : {:>5}".format(product, quantity)
      print(formatted_output)
      
  7. Formatting lists and tuples in Python:

    • Description: Format lists and tuples for output in a readable way.
    • Example Code:
      fruits = ['Apple', 'Banana', 'Orange']
      formatted_list = "Fruits: {}".format(", ".join(fruits))
      print(formatted_list)
      
  8. Customizing output with format specifiers in Python:

    • Description: Use format specifiers to control the appearance of variables in a formatted string.
    • Example Code:
      quantity = 10
      formatted_quantity = "Quantity: {:02d}".format(quantity)
      print(formatted_quantity)
      
  9. Pretty printing in Python for better output readability:

    • Description: Use the pprint module for more readable output of complex data structures.
    • Example Code:
      from pprint import pprint
      
      data = {'name': 'Charlie', 'age': 28, 'city': 'New York'}
      pprint(data)