Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

F-string usage in a print()

20 views
Skip to first unread message

Kevin M. Wilson

unread,
May 24, 2022, 5:14:58 PM5/24/22
to
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???
Caddy Man

Good sense makes one slow to anger, and it is his glory tooverlook an offense.

Proverbs 19:11

MRAB

unread,
May 24, 2022, 5:54:40 PM5/24/22
to
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))

Paul Bryan

unread,
May 24, 2022, 5:55:01 PM5/24/22
to
Try something like:

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

On Tue, 2022-05-24 at 21:14 +0000, 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???

Mats Wichmann

unread,
May 24, 2022, 6:21:57 PM5/24/22
to
On 5/24/22 15: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???


As noted elsewhere, your f-strings by themselves are fine, it isn't
complaining about those, though they're kind of silly as they don't do
any formatting that justifies entering them as f-strings. It's
complaining about this piece:

years + f"Future value = \n"

which is the second of the three comma-separated argument to print().
That's the int + string the error is grumping about.

Cameron Simpson

unread,
May 24, 2022, 7:45:36 PM5/24/22
to
On 24May2022 21:14, Kevin M. Wilson <kevinmwi...@yahoo.com> 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???

The short answer is that you cannot add (the "+" operator) a string to
an integer in Python because one is a numeric value and one is a text
value. You would need to convert the int to a str first if you really
wanted to. But in your code above, you don't need to.

Let's pick apart that print():

print(
f"Year = ",
years + f"Future value = \n",
future_value
)

Like any function, print()'s arguments are separate by commas. So you've
got 3 expressions there. The problematic expression looks like this
one:

years + f"Future value = \n"

You didn't supply a complete runnable example so we don't see "years"
get initialised. However, I assume it is an int because range() only
accepts ints. You can't add an int to a str.

Now, print() converts all its arguments to strings, so there's no need
for f-strings anywhere in this. I'd go:

print("Year =", years, "Future value =", future_value)

myself. If you really want that newline, maybe:

print("Year =", years, "Future value =")
print(future_value)

Format strings are for embedding values inside strings, which you don't
need to do in your code as written. And whether you wrote:

years + f"Future value = \n"

or:

years + "Future value = \n"

(because that string has no embedded values) it is still wrong because
years is an int and the string is still a str.

You _could_ use an f-string to compute the whole print line in one go:

print(f"Year = {years} Future value = \n{future_value}")

but I can't see the point, personally. I've code from people who prefer
that form though.

BTW, it helps people to help you if you supply a complete example. Your
example code did not initialise years or monthly_investment, and so will
not run for someone else. It also helps to winnow it down to the
smallest example you can which still shows the problem. FOr yoru example
you could have reduced things to this, perhaps:

years = 9
years + f"Future value = \n"

Cheers,
Cameron Simpson <c...@cskk.id.au>

Cameron Simpson

unread,
May 25, 2022, 12:06:39 AM5/25/22
to
On 25May2022 00:13, Kevin M. Wilson <kevinmwi...@yahoo.com> wrote:
>Cameron, I have a misunderstanding here, the 'f-string' is used when
>the str() is not...isn't it!

No, f-strings (format strings) are just a convenient way to embed values
in a string. The result is a string.

In days of yore the common formatting method was the % operator like C's
printf() format. You could do stuff like this:

print("%s: length is %d items" % (thing, len(thing)))

which would print something like:

Thing5: length is 12 items

Ignore the print() itself, that's just how you might use this: format a
string with 2 values, then print it out for a person to read.

You can do various things with %-formatting, but it is pretty limited
and a bit prone to pairing things up incorrectly (human error making the
"(thing, len(thing,len(thing)))" tuple) because those values are
separates from the string itself.

The funky new thing is format strings, where you can write:

print(f"{thing}: length is {len(thing)} items")

Again ignore the print(), we're really just interested in the
expression:

f"{thing}: length is {len(thing)} items"

which does the same thing as the %-format earlier, but more readably and
conveniently.

I suspect you think they have another purpose. Whereas I suspect you're
actaully trying to do something inappropriate for a number. If you've
come here from another language such as PHP you might expect to go:

print(some_number + some_string)

In Python you need compatible types - so many accidents come from mixing
stuff up.

You may know that print()'s operation is to take each expression you
give it and call str() on that value, then print that string.

f-strings have a similar operation: each {expression} inside one is
converted to a string for embedding in the larger format string; that is
also done with str() unless you've added something special in the {}
part.

Aside from output you should not expect to be adding strings and
numbers; - it isn't normally a sensible thing to do. And when printing
things, you need text (strings). But print() takes can of that by
passing every value to str(), which returns a string (in a manner
appropriate to the type of value). You only want f-strings or manual
joining up if you don't want the default separator between items (a
space).

Can you elaborate on _why_ you wanted an f-string? What were you doing
at the time?

Cheers,
Cameron Simpson <c...@cskk.id.au>
0 new messages