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

Zero Piraeus schesis at gmail.com
Sat Apr 14 18:35:32 EDT 2012


:

> 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'] = ''

Assuming item['description'] is a string, all you need is

>>> item['description'] = item['description'][:1]

Read up on string/sequence slicing if it isn't clear why that works.

> 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;

For that example:

>>> variable = 'element' in array

In both cases, a more general solution would be more complex ... note
that in your second question, you're not actually testing whether a
variable is set, but whether a dict has a value for a particular key.

 -[]z.



More information about the Python-list mailing list