Python: .format(), f-string/formatted string literals
There are actually two methods for formatting strings.
.format()
f-string
.format() method
we can format objects in our string using .format() method.
The above example is the simplest representation of .format() method.
We can also add multiple strings/data using this method.
We can also give index number inside the curly braces. Then it will print according to our indexing. For example:
Here, “C” is in the index 0, “Java” is in the index 1, “Python” is in the index 2.
Here, we have provided {2} three times. That’s why 3 times “Python” is printed.
We can also assign a name in the index. For example:
Formatting floating point number using .format() method:
Syntax: {value_name: width.precision f}
Here, the value of x is 1.23456789. But is we have to print up to 2 decimal places or 3 decimal places, then we can use this method. And here, width is the value of numbers before decimal point, but if the width is greater than the value, then it will print white spaces. If we provide 0 as width, will also print the exact value. For example:
f-strings/formatted string literals makes string interpolation easier
To create an f-string, we have to prefix the letter “ f ”. F-strings provide a concise and convenient way to embed python expressions inside string literals for formatting.
For example: