Python String Formatting: format() and f-strings (With Examples)
This Snippet is coded by a user inOnline python Compiler. You can see and run this code too.
زبان: python
Python offers two common ways to build formatted strings: the str.format() method and f-strings. format() uses replacement fields such as {0}, {name}, or {:,.2f} and fills them from positional or keyword arguments. F-strings, introduced in Python 3.6, prefix a string with f and evaluate expressions directly inside braces, making them concise and readable.
This example demonstrates positional and named placeholders, alignment and width specifiers, thousands separators, floating-point precision, integer base conversions, dynamic width/precision, and date/time formatting. Inputs are the values passed to format() or embedded in an f-string, combined with optional format specifications like >10, .2f, #x, or %Y-%m-%d. Outputs are new strings; the original values are not modified.
Both mechanisms support conversion flags such as !r for repr, nested replacement fields for dynamic specifications, and custom __format__ behavior for objects. String formatting runs in O(n) time relative to the length of the resulting string, since each character must be written to the output. F-strings are generally evaluated at runtime and are often faster and easier to read, while format() remains useful for reusable templates and older codebases. Use f-strings for local, readable interpolation and format() when a template needs to be stored and reused with different arguments.