I have searched the forums for a little bit now and I am still very confused. If someone could direct me to an article that explains this more in depth I would greatly appreciate it. I am taking an intro to python course and I found the solution to my problem, but I want to actually know how\why it works. The assignment is to return the batting average for a player, and display it as the MLB would display. So for example 4hits in 8 at bats would be .500. Here is the code I found that works.
from __future__ import division, print_function
def print_batting_average(at_bats, hits):
average_str = "%.3f" % (hits / at_bats)
if average_str.startswith("0"):
average_str = average_str[1:]
print("Batting average is", average_str)
print_batting_average(4, 2)
I know the % is modulus and gives the remainder of something. I just don’t understand how that fits into other parts of code. For example the “%.3f”. I have also seen the % used in different ways, and I just wanted to find a good explanation. Hopefully I don’t get flamed for positing this. Thanks for any help.
In the context you are asking about the
%is used to help format output, and has nothing to do with any mod operation.For instance,
%3d,%.2fare all different ways to format output. The first example means you want to display an integer and reserve 3 spaces for it. The 2nd one means you want to display a float type value with 2 numbers after the decimal point.See
String Formatting Operationsinhttp://docs.python.org/library/stdtypes.html#string-formatting-operations for more information and details about the various formatting types and options.
You may come across something like this:
yields:
The part enclosed in ‘ ‘ uses formatting instructions as place holders for the actual variable values supplied in toward the end of the line. The values are preceded by the % and then the () contain the variables that supply the values.
Here is a simple example as to why the format strings can come in handy for formatting your output:
Here we don’t reserve and additional space for the number and you can see it shifting the output when it reaches 10.
Here we format the number with two spaces, and get a leading blank space for single digit numbers.