ava*_*ans 5 python parentheses python-3.x f-string
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))
Run Code Online (Sandbox Code Playgroud)
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)})")
Run Code Online (Sandbox Code Playgroud)
Alternatively, you can remove the explicit parentheses:
print(f"range{-len(lst), len(lst)}")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
132 次 |
| 最近记录: |