1. Description of String.format() methods
In Python, the format() method is used to format strings by replacing placeholders within the string with specified values. The format() method provides a flexible way to create dynamic strings where certain parts of the string can be replaced by variables, values, or expressions.
2. Syntax and usage of the String.format() method
The syntax of the format() method is as follows:
1 |
formatted_string = string_to_format.format(value1, value2, ...) |
Here's a breakdown of the components:
- string_to_format: This is the original string that contains placeholders marked by curly braces {}. These curly braces define the positions where values will be inserted.
- value1, value2, ...: These are the values that will be inserted into the placeholders in the string_to_format. The number of values provided should match the number of placeholders in the string. The values can be variables, expressions, or any valid Python data type that can be converted to a string.
Placeholders can include optional format specifications inside curly braces to control the way the values are formatted. Format specifications are specified after a colon : within the curly braces.
Here are a few examples to illustrate the use of the format() method:
Example 1
1 2 3 4 5 |
name = "Hafid" age = 30 message = "Hello, my name is {} and I am {} years old.".format(name, age) print(message) # Output: Hello, my name is Hafid and I am 30 years old. |
Example 2 (using format specifications)
1 2 3 4 |
pi = 3.14159265359 formatted_pi = "The value of pi is {:.2f}".format(pi) print(formatted_pi) # Output: The value of pi is 3.14 |
In this example:
The format specification .2f : is used to round the value of pi to two decimal places.
You can use more advanced formatting options: such as field width, alignment, and more, by exploring the rich possibilities offered by Python's format mini-language.
Note
Keep in mind that in Python 3.6 and above, f-strings (formatted string literals) offer a more concise and readable way to format strings, making the format() method less commonly used in newer Python codebases.
Younes Derfoufi
CRMEF OUJDA
1 thought on “python String.format() methods”