Home > Net >  How to convert to Python 3
How to convert to Python 3

Time:11-17

I am in the process of converting Python 2 code into Python 3. Currently I am facing difficulty in converting the following code to Python 3. Please help.

print 'Data cache hit ratio: %4.2f%%' % ratio

Also, what %4.2f%% means?

Tried to rewrite the code with format().

CodePudding user response:

Just put parens around the parameters.

print('Data cache hit ratio: %4.2f%%' % ratio)

There are fancier ways of doing formatting in Python 3, but that will work.

%4.2f says "display this floating point number in a 4-character field with a decimal point and two places after. So, like "9.99". %% says "display a percent sign". The formatting here is straight from the C printf function.

CodePudding user response:

f denotes the fixed point notation. The value that precedes with % (4.2) is for denoting the width (4) and the precision (2) of the number respectively.

You can use either .format or f string

print("Floating point {0:4.2f}".format(ratio))

print(f' Floating point {ratio:4.2f}')

Here 4 is the total width of the field being printed, lefted-padded by spaces. 2 is the number of digits after the decimal point. You can read more about it here https://docs.python.org/3/library/string.html#format-specification-mini-language

  • Related