[newbie questions] if conditions - if isset - if empty

Jean-Michel Pichavant jeanmichel at sequans.com
Mon Apr 16 05:51:30 EDT 2012


Mahmoud Abdel-Fattah wrote:
> Hello, 
>
> I'm coming from PHP background ant totally new to Python, I just 
> started using scrapy, but has some generic question in python.
>
> 1. How can I write the following code in easier way in Python ?
> if len(item['description']) > 0:
>             item['description'] = item['description'][0]
>         else: 
>             item['description'] = ''
>
>
> In PHP I can write it as follows :
> $item['description'] = (len(item['description']) > 0) 
> ? item['description'][0] : '';
>
> So, is there similar way in Python ?
>
>
>
> 2. How can I check if this variable defined or not, in PHP I can use 
> isset();, in other way, how can I make the following syntax in Python ?
> $variable = isset($array['element']) ? true : false;
>
>
>
> Thanks a lot,
> Mahmoud

1. item['description'] = item.get('description', '')[1:] # access to a 
dict with a default value if the key does not exist, then slice the result

2. if we're talking about dictionnaries, then you can test easily writing
if 'description' in item :
    pass # whatever
It works in python with any iterable.

Cheers,

JM




More information about the Python-list mailing list