F-string usage in a print()

MRAB python at mrabarnett.plus.com
Tue May 24 17:54:10 EDT 2022


On 2022-05-24 22:14, Kevin M. Wilson via Python-list wrote:
> future_value = 0
> for i in range(years):
> # for i in range(months):
>     future_value += monthly_investment
>     future_value = round(future_value, 2)
>     # monthly_interest_amount = future_value * monthly_interest_rate
>     # future_value += monthly_interest_amount
>     # display the result
>     print(f"Year = ", years + f"Future value = \n", future_value)When joining a string with a number, use an f-string otherwise, code a str() because a implicit convert of an int to str causes a TypeError!Well...WTF! Am I not using the f-string function correctly...in the above line of code???
> 
There's no implicit conversion. An f-string always gives you a string.

'years' is an int, f"Future value = \n" is a str, and you can't add an 
int and a str.

Maybe you meant this:

     print(f"Year = {i}, Future value = {future_value}")

or this:

     print(f"Year = {i + 1}, Future value = {future_value}")

These are equivalent to:

     print("Year = {}, Future value = {}".format(i, future_value))

and:

     print("Year = {}, Future value = {}".format(i + 1, future_value))


More information about the Python-list mailing list