In the following code I output the range of values which I can use to index the list lst
.
However, due to some oddity of Python's format literals the output contains two opening and two closing parentheses instead of one.
I don't see what's wrong with my format string. I just put all expressions which should be substituted in curly braces. The rest should not be substituted.
lst = [1,2,3,4,5,6]
print(f"range({-len(lst), len(lst)})")
> range((-6, 6))
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.
Anything that is not contained in braces is considered literal text, which is copied unchanged to the output. If you need to include a brace character in the literal text, it can be escaped by doubling: {{ and }}.
The f means Formatted string literals and it's new in Python 3.6 . A formatted string literal or f-string is a string literal that is prefixed with 'f' or 'F' . These strings may contain replacement fields, which are expressions delimited by curly braces {} .
The expression -len(lst), len(lst)
is a tuple. Usually it's the comma that makes a tuple, not the parentheses. So your output shows the outer parentheses that you explicitly wrote, and the inner parentheses from the tuple. To avoid that, have a separate format for each item you want to print:
print(f"range({-len(lst)}, {len(lst)})")
Alternatively, you can remove the explicit parentheses:
print(f"range{-len(lst), len(lst)}")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With