String formatting in Python allows you to build strings dynamically by injecting values. You can use the format()
method, f-strings (Python 3.6+), or older formatting styles.
# Example 1: Using format() with positional arguments
print("Hello, {}!".format("John")) # Hello, John!
# Example 2: Using format() with named arguments
print("Name: {name}, Age: {age}".format(name="Doe", age=55))
# Example 3: f-strings (recommended)
name = "Pooja"
age = 30
print(f"{name} is {age} years old") # Pooja is 30 years old
# Example 4: Formatting numbers with f-strings
pi = 3.14159
print(f"Pi rounded to 2 decimals: {pi:.2f}") # Pi rounded to 2 decimals: 3.14
# Example 5: Padding and alignment
print("{:<10} | {:^10} | {:>10}".format("Left", "Center", "Right"))
# Left | Center | Right