我有两个名称要显示在单个打印语句上,以及是否为一个组选择了它们并希望输出如下所示: “帐户名:John(独立)帐户名:Russel(高级)” 我的名字位于 account.name 下,我使用 account.group 来表示 True 或 False 陈述,所以我想了解如何执行以下操作。
account1 = accounts(self, name, group)
account2 = accounts(self, name, group)
account1.name = "John"
account2.name = "Russel"
account1.group = False
account2.group = True
print (f"account name: {str(account1.name)} if account1.group is True {str"(Premium)"} else {str"
(Unaffiliated)":10} f"account name: {str(account2.name)} if account2.group is True {str"(Premium)"} else
{str"(Unaffiliated)"}\n")
我不确定如何或是否可以插入这样的 if 语句,或者有什么更有效的方法来获得我正在寻找的东西,但欢迎任何建议。 顺便说一句,创建了一个名为 account 的类,但我认为它与插入我的示例中无关
我默认收到语法错误,这并不让我感到惊讶。
您可以使用三元运算符来实现此目的。
print(f'{"Premium" if account.name is True else "Unaffiliated"}')
但是,应该注意的是,在 f 字符串中放入太多内容会对代码的可读性产生负面影响,建议在此类方面使用变量或 .format() 方法。