Search code examples
pythonstringlambdaconcatenationstring-concatenation

How to concatenate a string returned by a lambda with other strings?


I'm trying to use a lambda to check if an object (self)'s attribute problematic_object is None. If it is, it should return a "" (an empty string), and if not, str(self.problematic_object). I've tried doing it in 3 ways:

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 ""

I get this error in all the cases:

SyntaxError: invalid syntax

I know that this can be done using a normal if-else, but is there any way I can do it using a lambda? This is my first time using a lambda and this kind of an if-else. What is the mistake I'm making? Can a lambda be used like this?


Solution

  • If self.problematic_object is possibly None, and in that case you just want an empty string, simply use f-strings to add it to your overall string. No need for any boolean logic:

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

    If self.problematic_object is None then nothing will be added to the end of the string. If it's not None then its value will be added.