Python str.format() function
In Python, the str.format()
method is used to format strings by embedding values within a string using placeholders. This method provides a powerful way to create formatted output and is widely used for constructing strings in a readable and maintainable way.
Syntax
*args
: Positional arguments that can be passed to the placeholders in the string.**kwargs
: Keyword arguments that can also be used in the placeholders.
Placeholders
Placeholders in the string are defined using curly braces {}
. You can use various options within the braces to specify formatting options, such as number formatting, alignment, width, and more.
Example Usage
- Basic formatting with positional arguments:
- Using indexed placeholders:
You can use indexed placeholders to refer to specific arguments:
- Using keyword arguments:
You can also use named placeholders with keyword arguments:
- Formatting numbers:
You can format numbers, including decimal places and thousands separators:
- Alignment and width:
You can control the alignment and width of the formatted output:
- Using format specifiers:
You can use format specifiers for more advanced formatting:
Summary
- Use
str.format()
to format strings dynamically by embedding values within placeholders. - You can use both positional and keyword arguments for flexibility in formatting.
- The method allows for various formatting options, including number formatting, alignment, and width control.
- This method is a powerful tool for constructing readable and maintainable output strings in your applications.
Note on f-strings
Starting from Python 3.6, f-strings (formatted string literals) are also available and provide a more concise syntax for string formatting. For example:
F-strings are often preferred for their simplicity and readability, but str.format()
remains a powerful and flexible option.