Python % operator for String Interpolation

DevTechie
DevTechie
Published in
5 min readApr 10, 2024

--

Python % operator for String Interpolation

You may be surprised to know that there are many ways to format strings in Python. Before Python 3.6, there were two basic tools for interpolating (mixing) values, variables, and expressions within string literals:

1 — The string interpolation operator (%) (the math’s modulo operator)

2 — The string.format() method

They may be considered ‌Conventional String Formatting. This article talks about the first one — “%” operator for string formatting.

% operator

In Python, strings feature a unique built-in operation implemented by the % operator. Yes! You got it right, the `%` operator besides being a modulus operator, it is also a string formatting operator in Python. It is used to format strings by replacing placeholders with values.

% operator is also known as string interpolation operator in Python.

This makes simple positional formatting very easy. If you’ve ever used the printf function in C, you’ll understand how this works immediately.

In the below code snippet, I’m using the %s format specifier to inform Python where to substitute the value of the placeholder which is represented as a string.

name = "Akhanda"

--

--