F-string usage in a print()
Cameron Simpson
cs at cskk.id.au
Tue May 24 23:15:34 EDT 2022
On 25May2022 00:13, Kevin M. Wilson <kevinmwilson1956 at 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 <cs at cskk.id.au>
More information about the Python-list
mailing list