As pointed out in the comments, a good comparison of string formatting methods is provided on the Real Python website.
f-strings in many situations can be more readable and less human-error prone to code than other variants, but require Python >= 3.6, so may have to be avoided if backwards compatibility is required. In general they are a good choice though, up to a few gotchas that come up from time to time.
When nesting f-strings you have to be careful with quotation marks. This fails:
>>> f"Hello {"there"}"
File "<stdin>", line 1
f"Hello {"there"}"
^
SyntaxError: invalid syntax
But using other quotation marks on the inside lets you get around this:
>>> f"Hello {'there'}"
'Hello there'
You cannot nest f-strings containing string literals deeper than that though, because you have no further different quotation marks to use.
Another gotcha I stumble across regularly is the restriction on not allowing backslashes in the f-string expression part, even if they are inside a string literal:
>>> f"Path: {'C:\Windows'}"
File "<stdin>", line 1
SyntaxError: f-string expression part cannot include a backslash
You can get around that using an intermediate variable, or format()
:
>>> path = 'C:\Windows'
>>> f"Path: {path}"
'Path: C:\\Windows'
>>> "Path: {0}".format('C:\Windows')
'Path: C:\\Windows'
This is probably the issue you had with using f-strings to format paths. I personally tend to encounter this limitation when working with string literals that have newlines '\n'
in them inside the f-string expression part.