7

Can someone help me with the explanation of what the "'f %" meaning in the following code?

print('Slope: %.3f' % lr.w_[1])
3
  • Just a comment: This is old string notation. Have a look at str.format() instead.
    – Anton vBR
    Jul 13, 2018 at 15:16
  • 1
    @Anton vBR building off of that, here is OPs code converted to use .format : print('Slope: {.3f}'.format(lr.w_[1])
    – Woohoojin
    Jul 13, 2018 at 15:18
  • If I may, it should be print('Slope: {:.3f}.format(lr.w_[1]). There was a : missing in @Woohoojin's comment Jul 20, 2022 at 10:57

3 Answers 3

8

Here is a list of string formatting options in Python. You use a % as a placeholder, which is replaced by lr.w_[1] in this case. The f then refers to "Floating point decimal format". The .3 indicates to round to 3 places after the decimal point.

5

It prints a decimal number, with 3 decimal digit accuracy.

In [1]: print('Slope: %.3f' % 1.123)
Slope: 1.123

In [2]: print('Slope: %.3f' % 1.12345)
Slope: 1.123

In [3]: print('Slope: %.3f' % 1.1)
Slope: 1.100

In [4]: print('Slope: %.3f' % 1.1237)
Slope: 1.124

As you can see by the 4th example is rounds by standard rounding rules

5
%.3f

f: Floating point, which means that the value that is going to be printed is a real number.

.3 is for the number of decimals after the point. That means that the real value to be printed will have 3 digits after the point.


For example:

print('%.3f' % 3.14159)          # Prints 3.142
print('%.2f' % 3.141592653589)   # Prints 3.14
2
  • 1
    "f" stands for floating point. The integer (here 3) represents the number of decimals after the point. "%.3f" will print a real number with 3 figures after the point.
    – Kefeng91
    Jul 13, 2018 at 15:17
  • @Kefeng91 I missed that this was in question too. Thank you very much, answer updated!
    – gsamaras
    Jul 14, 2018 at 13:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.