Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python lambda returning None instead of empty string

Tags:

python

lambda

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.

like image 240
Virgiliu Avatar asked Apr 03 '10 20:04

Virgiliu


People also ask

How do you change a None to an empty string in Python?

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.

Is None same as empty string?

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.

Can Lambda return 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.

How do you show empty strings in Python?

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.


2 Answers

use the if else construct

f = lambda x:'' if x is None else x
like image 152
z33m Avatar answered Oct 10 '22 20:10

z33m


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 ''
like image 39
Yaroslav Avatar answered Oct 10 '22 20:10

Yaroslav