Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

237
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda