Shortening Python Lambda

时间:2015-07-08 15:50:23

标签: python-2.7

The code below takes a value and returns it if the value is of basestring. If the the value is not of basestring, then convert it to a string, but if the value is None, then return an empty string.

Is there a more Pythonic way of doing this?

lambda value: value if isinstance(value, basestring) else str(value) if value is not None else ""

1 个答案:

答案 0 :(得分:6)

I wouldn't even bother checking if it is a string, just convert it regardless (This will work in Python 3.x but not 2.x).

lambda value: str(value) if value is not None else ""

The reason is that if it is already a str, then calling str() will basically do nothing.

>>> s = 'test'
>>> id(s)
35584672
>>> id(str(s))
35584672
>>> j = str(s)
>>> id(j)
35584672

Notice they all have the same id? This means no new object was created.