I have the following lambda function:
f = lambda x: x == None and '' or x
It should return an empty string if it receives None as the argument, or the argument if it's not None.
For example:
>>> f(4)
4
>>> f(None)
>>>
If I call f(None) instead of getting an empty string I get None. I printed the type of what the function returned and I got NoneType. I was expecting string.
type('') returns string, so I'd like to know why the lambda doesn't return an empty string when I pass None as an argument.
I'm fairly new to lambdas so I might have misunderstood some things about how they work.
Method #2 : Using str() Simply the str function can be used to perform this particular task because, None also evaluates to a “False” value and hence will not be selected and rather a string converted false which evaluates to empty string is returned.
None is not the same as 0, False, or an empty string. None is a data type of its own (NoneType) and only None can be None.
"lambda: None" might be used either where a function returning an Optional[T] is expected, or where a function not returning a value is expected.
String len() It is valid to have a string of zero characters, written just as '' , called the "empty string". The length of the empty string is 0. The len() function in Python is omnipresent - it's used to retrieve the length of every data type, with string just a first example.
use the if else construct
f = lambda x:'' if x is None else x
The problem in your case that '' is considered as boolean False. bool('') == False. You can use
f =lambda x:x if x is not None else ''
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With