Odd listcomp behaviour
MRAB
python at mrabarnett.plus.com
Fri Dec 17 18:29:45 EST 2010
On 17/12/2010 23:08, Emile van Sebille wrote:
> Does anyone else consider this a bug?
>
> Python 2.6.2 (r262:71600, Jun 16 2009, 11:09:39)
> [GCC 3.4.6 20060404 (Red Hat 3.4.6-10)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>
> ---1---
> >>> skippedords = '1,2,3,4,5'
> >>> ['10%s' % ii for ii in skippedords.split(',')]
> ['101', '102', '103', '104', '105']
>
> ---2---
> >>> skippedords = ''
> >>> ['10%s' % ii for ii in skippedords.split(',')]
> ['10']
>
> ---3---
> >>> test = ''
> >>> ['%s' % ii for ii in test.split() ]
> []
>
>
> I got stung because I expected ---2--- to do what ---3--- did.
>
It's not a bug. The third example is the odd one out because it splits
on a sequence of one or more (whitespace) characters and discards empty
strings. For example:
>>> ',,1,,2,,'.split(',')
['', '', '1', '', '2', '', '']
>>> ' 1 2 '.split(' ')
['', '', '1', '', '2', '', '']
>>> # But...
>>> ' 1 2 '.split()
['1', '2']
More information about the Python-list
mailing list