'Should I use f-strings? [duplicate]
These two print
statements produce the same results and at least to me the first version looks more readable.
Should I stick with the f'
version because it will cause issues for me later on or cause worse performance or does not follow the present Python standards? Or is it only a question of consistent usage of one of these versions?
print('My first bicycle was a ' + bicycles[1])
print(f'My first bicycle was a {bicycles[1]})')
Solution 1:[1]
From PEP 498, a PEP (Python Enhancement Proposals) dedicated to Literal String Interpolation,
F-strings provide a way to embed expressions inside string literals, using a minimal syntax. It should be noted that an f-string is really an expression evaluated at run time, not a constant value. In Python source code, an f-string is a literal string, prefixed with âfâ, which contains expressions inside braces. The expressions are replaced with their values.
The main point here is the highlighted text. That means it is way better in evaluation due to the internal implementation of ASTs (abstract syntax trees) by the CPython compiler which makes them fast.
Also, I think it is more readable and in case of more variables in your string it provides better readability. Multi-line string interpolation can be performed easily using this syntax.
For example,
f'''
My first bicycle was a {bicycles[0]}
It has color {bicycles[0]["color"]}
and has {bicycles[0]["gears"]} gears.
'''
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Peter Mortensen |