In python, string formatting can be done by using a string format() method. To format the strings, you need to add curly braces { }
in the text so that the format() method will use those curly braces { }
as placeholders to replace them with the required content.
Following is the syntax of format()
method in python to format the strings.
The python format() method will accept unlimited parameters and replace the curly brace { }
placeholders with the content of the respective parameters.
Following is the example of formatting strings in python using format()
method.
If you observe the above example, we created strings with single and multiple placeholders (curly brace { }
) to replace with required parameter values using format()
method.
When you execute the above python program, you will get the result as shown below.
To make sure the arguments are replaced in the correct order, you can define the positional or keyword arguments in the placeholders like as shown below.
If you observe the above example, we defined the placeholders with positional and keyword arguments to specify the order.
When you execute the above python program, you will get the result as shown below.
In python, you can also format the placeholder's text by using different formatting types like <, >, ^, etc., based on your requirements.
Following is the example of formatting the placeholder’s text by using different format types in python.
If you observe the above example, we used different format types inside of placeholders { }
to format the placeholder's text based on requirements.
When you execute the above python program, you will get the result as shown below.
To know more about formatting types in placeholders, refer python string format() method.
This is how you can perform string formatting in python using the format() method with different formatting types based on your requirements.