Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

238
Views
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?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!