Python - is it possible to use lambda in print with format (f or .format)?

Asked

Viewed 82 times

0

I searched for lambda and print and I didn’t find anything I imagined, I mean, it’s possible to do something like this:

mil = num//1000
print(f'O número tem {mil} {lambda milhar if (mil == 1) else milhares}')

or

print('O número tem {} {}'. format(mil, lambda milhar if (mil == 1) else milhares)

Thank you.

2 answers

1

What you need in this case is not lambda, but use ternary operator. Follow an example:

num = 1200
mil = int(num/1000)
print("o numero tem {} {}".format(mil, "milhar" if mil == 1 else "milhares"))
  • Renan, perfect solved the problem of my code, in fact completely forgot the ternary. However, is the question, print format and lambda work together? I haven’t found an example yet, maybe I can’t. Thank you very much.

1


As already mentioned by Renan, the problem can be solved easier through the use of the ternary operator, however, it is possible to add the lambda along with the print.

num = 3000
mil = num//1000

# Utilizando lambda
print(f'O número tem {mil} {(lambda : "milhar" if mil == 1 else "milhares")()}')

# Utilizando apenas operador ternário
print(f'O número tem {mil} {"milhar" if mil == 1 else "milhares"}')

The lambda ultimately returns an expression, so it needs to be called (call) to return the value.

  • 1

    Camilo, thank you very much. Believe me, I had mounted this lambda that you created, but without both () at the end, because I had not seen them in the lambda examples that I found around. Now it became clear the character of the lambda 'an expression', should be called. It worked perfect, as you already knew. Thanks.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.