Explain the Python String Formatting
Explain the Python String Formatting
Student
The Anubhav portal was launched in March 2015 at the behest of the Hon'ble Prime Minister for retiring government officials to leave a record of their experiences while in Govt service .
There are four main ways to format strings in Python, each evolving with the language.
1. Old Style Formatting (
%Operator)This is similar to C’s
printfformatting.Output:
Common format specifiers:
%s'Anna'%d25%f25.000000%.2f25.002.
str.format()Method (Introduced in Python 2.6+)This method uses
{}placeholders inside strings.Output:
You can also use indexes or named arguments:
Formatting numbers:
Output:
3. Formatted String Literals (f-Strings) — Python 3.6+
This is the modern and most readable way.
You prefix the string with
forF, and expressions inside{}are evaluated directly.Output:
You can also use expressions inside
{}:Number formatting:
Output:
Alignment and width:
Output:
4. Template Strings (from
stringmodule)Useful when you want safe substitutions (e.g., user input).
Output:
If you use
.safe_substitute()instead, it won’t raise an error if a placeholder is missing.Comparison Summary
%"Hello %s" % name.format()"Hello {}".format(name)f""f"Hello {name}"TemplateTemplate("Hello $name")Example Summary