which is more 'pythonic' / 'better' ?
Will McGugan
news at NOwillmcguganSPAM.com
Mon Sep 12 07:44:56 EDT 2005
gabor wrote:
> hi,
>
> there are 2 versions of a simple code.
> which is preferred?
>
>
> ===
> if len(line) >= (n+1):
> text = line[n]
> else:
> text = 'nothing'
> ===
>
>
> ===
> try:
> text = line[n]
> except IndexError:
> text = 'nothing'
> ===
>
>
> which is the one you would use?
I would actualy use the following for this particular case..
text = line[n:n+1] or 'nothing'
But in general I think it is best to use exceptions like that only where
you expect the code to _not_ throw the exception the majority of
times. Otherwise the simple condition is better. Although I expect there
is not much difference either way..
Will McGugan
--
http://www.kelpiesoft.com
More information about the Python-list
mailing list