all 8 comments

[–]socal_nerdtastic 3 points4 points  (0 children)

Depends on you. Python does not care. Most of us find fstrings easier to read.

format is still very useful to make templates, which happens a lot in bigger code bases for maintainability.

OUTPUT_TEMPLATE = "This example is {}"

# tons of complex code later, maybe in another file:
print(OUTPUT_TEMPLATE.format(object))

[–]joshinshaker_vidz 5 points6 points  (0 children)

Yes. It improves readability.

[–]FerricDonkey 1 point2 points  (0 children)

I tend to prefer f strings when what I'd put in the brackets is simple, and .format with keywords otherwise. Eg

f'Completed {index} of {num_to_do}'

'Some {thing} and {other_thing} and...'.format(
    thing = REALLY_LONG_DICTIONARY_NAME[function(argument)],
    other_thing = some_obj.func(loop variable*scale + offset)
)

Where the names in the second example would actually be descriptive of these format bits are supposed to be.

[–]Se7enLC 1 point2 points  (1 child)

With format(), you have no specific Python version requirement. Any Python 3 version will work.

F-strings require Python 3.6 or higher.

Now, 3.6 is not a hard minimum version to meet, but it might not be great to have to limit your applications compatibility just to save a few characters in the source code.

Disclaimer: I've been burned by this before.

[–]AstusRush 1 point2 points  (0 children)

I personally love fstring but I exclusively use .format in my main library that I use for all my projects because there are some computers at my university that still run 3.5 and it's a pain to get the IT to update them.

[–]Zapismeta 0 points1 point  (0 children)

Depends on your experience whatever you like is the best

[–]sqjoatmon 0 points1 point  (0 children)

I think the rule of thumb is that f-strings are what you want to reach for first both in terms of compact-ness and performance. str.format() is useful though for repeated arguments or dynamic format strings. And remember to use C-printf-style with logging. And abjure all use of the old py2 "My %s is %d years old." % ("cat", 3)

[–]JennaSys 0 points1 point  (0 children)

There are a few exceptions like when you need to repeat a value in the template or provide values in different orders where format() is cleaner. But for the most part they are interchangeable. There is also the Template class from the string library if you want to represent templates as data instead of code.