0% found this document useful (0 votes)
3 views27 pages

Python String Formatting Techniques

Uploaded by

nabigha safdar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views27 pages

Python String Formatting Techniques

Uploaded by

nabigha safdar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

[Link]

org/try-jupyter/lab/

[Link]
[Link]

[Link]
Old string formatting (Optional)
The format() method was introduced in Python 2.6. Before that, the % (modulo) operator could be
used to get a similar result. Although this method is no longer recommended for new code, you might
come across it in someone else's code. This is what it looks like:

"base string with %s placeholder" % variable

The % (modulo) operator returns a copy of the string where the placeholders indicated by % followed
by a formatting expression are replaced by the variables after the operator.

To replace more than one value, you need to supply the values as a tuple. The formatting expression
must match the value type.

"base string with %d and %d placeholders" % (value1, value2)

Variables can also be replaced by name using a dictionary syntax (you’ll learn about dictionaries in an
upcoming video).

print("%(var1)d %(var2)d" % {"var1":value1, "var2":value2})

The formatting expressions are mostly the same as those of the format() method.

"Item: %s - Amount: %d - Price: %.2f" % (item, amount, price)

You might also like