-1

For older version of Python, one can print the string as such:

>>> print('X = %6.4f' % 12312312.423141)
X = 12312312.4231

And in Python < 3.6, putting a float into a formatted string and printing the string. In modern python, one could have done:

>>> print('X = {num}'.format(num=round(12312312.423141, 4)))
X = 12312312.4231

But that's explicitly rounding the float to 4 decimal points. Is there a way to print the float as in the old way by stating the 6-place field to the 4 decimal points? E.g. https://stackoverflow.com/a/15215445/610569

For Python > 3.6, how about fstring? Would it look like this?

>>> num=12312312.423141
>>> print(f'X = {num:6.4f}')
alvas
  • 115,346
  • 109
  • 446
  • 738

2 Answers2

4

I am not sure what you are asking, but to answer the question in the title:

The new python3.6 version of 'X = %6.4f' % 12312312.423141 is, as you said f'X = {12312312.423141:6.4f}'

The below python3.6 version is 'X = {num:6.4f}'.format(num=12312312.423141)

MegaIng
  • 7,361
  • 1
  • 22
  • 35
-1

Yes, I can use the %6.4f in the str.format() and f'...' string too.

In Python >= 3.6:

>>> num=12312312.423141
>>> 'X = %6.4f' % num == 'X = {num:6.4f}'.format(num=num) == f'X = {num:6.4f}'
True

>>> print('X = %6.4f' % num)
X = 12312312.4231

>>> print('X = {num:6.4f}'.format(num=num))
X = 12312312.4231

>>> print(f'X = {num:6.4f}')
X = 12312312.4231

And the docs:

alvas
  • 115,346
  • 109
  • 446
  • 738