Formatting Strings—Modulus

Although not actually modulus, the Python % operator works similarly in string formatting to interpolate variables into a formatting string. If you've programmed in C, you'll notice that % is much like C's printf(), sprintf(), and fprintf() functions.

There are two forms of %, one of which works with strings and tuples, the other with dictionaries.

StringOperand % TupleOperand

StringOperand % DictionaryOperand

Both return a new formatted string quickly and easily.

% Tuple String Formatting

In the StringOperand % TupleOperand form, StringOperand represents special directives within the string that help format the tuple. One such directive is %s, which sets up the format string

 >>> format = "%s is my friend and %s ...

Get Python Programming with the Java™ Class Libraries: A Tutorial for Building Web and Enterprise Applications with Jython now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.