Short answer: there's no difference between the two.
In the first example you provided (print(f"Miles Per Gallon:\t\t {mpg}")
), you're doing something in Python called formatting. It's a pretty useful concept that can come in handy when you want to put lots of things in one string without having to concatenate all of them.
In your second example, print("Miles Per Gallon: \t\t " + str(mpg))
, instead of using formatting, you're converting mpg
to a string
, and then telling python to "concatenate" (merge) the two (the string to the left and the string to the right) together. +
in Python will both concatenate and add numbers, depending on the types of the variables surrounding it.
Formatting in Python becomes very useful when you need to put a lot of things in one string. For example, let's say I want to print the value of 3 variables, a
, b
, and c
, and I want to label them. For the sake of example, we'll say that we don't know if the variables are type int
or str
; this is important, because it means we need to explicitly convert them to a string, otherwise we run the risk of Python throwing a TypeError (specifically, TypeError: can only concatenate str (not "int") to str
). To do this with concatenation (as your second example does), this is what would be done:
"The value of a is " + str(a) + ", b is " + str(b) + ", c is " + str(c)
As you can see, that can be kind of messy, which is where formatting comes in to play. There are lots of ways to format strings in Python. I'll use yours in addition to another common one, but it's entirely personal preference which you would like to use.
f"The value of a is {a}, b is {b}, c is {c}"
"The value of a is {0}, b is {1}, c is {2}".format(str(a), str(b), str(c))
This is a lot cleaner, and makes for more easily readable code than concatenation, as well as making editing it less of a headache. More info on various ways of formatting string is available in the documentation here.
Hope this helps!