如何将lambda返回的字符串与其他字符串连接起来



我正在尝试使用lambda来检查对象(self(的属性problematic_object是否为None。如果是,它应该返回一个""(一个空字符串(,如果不是,则返回str(self.problematic_object)。我尝试了三种方法:

1:

def __str__(self):
return "string1" + str(self.object) + "n" + "string2" + self.another_object + "n" + "string3" + exec(lambda self: str(self.problematic_object) if self.problematic_object!=None else "")

2:

def __str__(self):
return "string1" + str(self.object) + "n" + "string2" + self.another_object + "n" + "string3" + (lambda self: str(self.problematic_object) if self.problematic_object!=None else "")

3:

def __str__(self):
return "string1" + str(self.object) + "n" + "string2" + self.another_object + "n" + "string3" + lambda self: str(self.problematic_object) if self.problematic_object!=None else ""

我在所有情况下都会遇到这个错误:

SyntaxError:无效语法

我知道这可以使用普通的if-else来完成,但有什么方法可以使用lambda来完成吗?这是我第一次使用lambda和这种if-else。我犯了什么错误?lambda可以这样使用吗?

如果self.problematic_object可能是None,在这种情况下,您只需要一个空字符串,只需使用f-string将其添加到整个字符串中。不需要任何布尔逻辑:

def __str__(self):
return f"string1{self.object}nstring2{self.another_object}nstring3{self.problematic_object}"

如果self.problematic_objectNone,则不会向字符串的末尾添加任何内容。如果它不是None,那么它的值将被相加。

相关内容

最新更新