简体   繁体   English

为什么此打印语句使用 Python f-string output 双括号?

[英]Why does this print statement using a Python f-string output double parentheses?

In the following code I output the range of values which I can use to index the list lst .在下面的代码中,我 output 可以用来索引列表lst的值范围。 However, due to some oddity of Python's format literals the output contains two opening and two closing parentheses instead of one.然而,由于 Python 的格式文字有些奇怪,output 包含两个左括号和两个右括号,而不是一个。 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.不应替换 rest。

lst = [1,2,3,4,5,6]
print(f"range({-len(lst), len(lst)})")
> range((-6, 6))

The expression -len(lst), len(lst) is a tuple.表达式-len(lst), len(lst)是一个元组。 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.因此,您的 output 显示了您明确编写的外括号,以及元组中的内括号。 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)}")

You should have put the curly brackets individually, not in whole.您应该单独放置大括号,而不是全部放置。 Like:喜欢:

print(f"range({-len(lst)}, {len(lst)})")

If that doesn't work then I don't know any other solutions.如果这不起作用,那么我不知道任何其他解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM