Back to course

String Formatting 1: The Old School (%) and `.format()`

Python Programming: The 0 to Hero Bootcamp

String Formatting Techniques

Formatting allows us to insert variable values into strings easily and cleanly.

1. The Old Style Formatting (C-style % operator)

This method is rarely used in modern Python but you might encounter it in legacy code.

python name = 'Alex' age = 30

output = "Hello, my name is %s and I am %d years old." % (name, age) print(output)

%s: string

%d: integer

%f: float

2. The .format() Method

Introduced in Python 3, this uses curly braces {} as placeholders.

Positional Formatting

Values are inserted based on their order.

python print("The first number is {}, and the second is {}.".format(10, 20))

Output: The first number is 10, and the second is 20.

Index Formatting

You can specify the index of the argument to use.

python print("I love {0}, {1}, and {0} again.".format('apples', 'bananas'))

Output: I love apples, bananas, and apples again.

Keyword Formatting

Use names inside the placeholders, making the code much more readable.

python print("Today's weather: High of {high}°C, Low of {low}°C.".format(low=10, high=25))

Output: Today's weather: High of 25°C, Low of 10°C.