x = 3.14159265 print(f'pi = {x:.2f}') # 3.14
Here is what the above code is Doing:
1. We’re using the f-string syntax to insert the value of x into the string.
2. We’re using the :.2f format specifier to tell Python to use 2 decimal places when printing the value of x.
3. We’re using the format() method to insert the value of x into the string.
4. We’re using the :.2f format specifier to tell Python to use 2 decimal places when printing the value of x.
The output of the code is:
pi = 3.14
You can use the format() method to format a string with the same syntax as the f-string.
The format() method is more flexible than the f-string. For example, you can use the format() method to align the output.
Here’s an example: