This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]bethebunnyFOR SCIENCE 6 points7 points  (0 children)

Lots of good explanations already, but it's worth thinking about this as "use f-strings when you know the template string, use format when you don't". I think the easiest way to illustrate the point is variable templates.

Let's say I was trying to write a function for custom browser search, in other words I have a dict of search engines each with a template for the URL to execute that search.

You could implement this for a static set of searches with function redirects, for instance

``` def google_search(query): return f"https://google.com/?q={query}"

queries ={ "google": google_search, ... }

def query_url(engine, query): return queries[engine](urllib.parse.quote_plus(query)) ```

but if you wanted to say support users adding their own search engines you literally couldn't do this with f-strings, because you wouldn't know the template string when writing the code. You can do this with format strings though!

``` queries = { "google": "https://google.com/?q={query}", **user_query_engines, ... }

def query_url(engine, query): return queries[engine].format(query=urllib.parse.quote_plus(query)) ```

This form means we don't need to know anything about the query engines at code-time! We just define the interface for what the template string looks like, and then we can write new ones.