mapping None values to ''
Jean-Paul Calderone
exarkun at divmod.com
Sun Jun 18 13:28:36 EDT 2006
On Sun, 18 Jun 2006 07:37:00 -0500, Tim Chase <python.list at tim.thechases.com> wrote:
>> i wish to map None or "None" values to "".
>> eg
>> a = None
>> b = None
>> c = "None"
>>
>> map( <something> , [i for i in [a,b,c] if i in ("None",None) ])
>>
>> I can't seem to find a way to put all values to "". Can anyone help?
>> thanks
>
>I'd consider this a VeryBadIdea(tm). However, given Python's
>introspective superpowers, it *can* be done (even if it most
>likely *shouldn't* be done). That caveat out of the way, here goes:
>
> >>> for scope in [locals, globals]:
>... s = scope()
>... for vbl, value in s.items():
>... if value == None or (type(value) == type("") and
>value == 'None'):
>... s[vbl] = ''
>
Hey Tim,
Actually this doesn't work for locals at all:
>>> def f():
... x = 'x'
... locals()['x'] = 'y'
... print x
...
>>> f()
x
>>>
Locals cannot be modified through the dict returned by locals().
>
>There may be some better way to determing whether an item is a
>string than my off-the-cufff
>
> type(value) == type("")
>
Yes. isinstance(value, str) is the best way to do this.
Jean-Paul
More information about the Python-list
mailing list