Code %s/%d/%f


whats the difference between %s, %d, %f. when I switched between them, the code works identically.


%s specifies a string placeholder

%d specifies a digit placeholder

%f specifies a float placeholder.

Study the following example…

>>> from math import pi
>>> print ("%s %d %f" % (pi, pi, pi))
3.141592653589793 3 3.141593

The first value is cast to string, then inserted, the second is converted to integer then cast to string and inserted, the third is rounded to six digit precision and cast to a string and inserted.

The float precision can be displayed the same as the string representation.

>>> print ("%s %d %.15f" % (pi, pi, pi))
3.141592653589793 3 3.141592653589793

or we can push the envelope to find a maximum…

>>> print ("%s %d %.64f" % (pi, pi, pi))
3.141592653589793 3 3.1415926535897931159979634685441851615905761718750000000000000000
>>> print ("%s %d %.127f" % (pi, pi, pi))
3.141592653589793 3 3.1415926535897931159979634685441851615905761718750000000000000000000000000000000000000000000000000000000000000000000000000000000
>>> print ("%s %d %.49f" % (pi, pi, pi))
3.141592653589793 3 3.1415926535897931159979634685441851615905761718750

Looks like 48 decimal place precision is the limit…


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.