Odd listcomp behaviour

Ethan Furman ethan at stoneleaf.us
Fri Dec 17 18:28:33 EST 2010


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 stung me too (more times than I care to admit! ;), but it's not a bug.

2.5 docs:
split( [sep [,maxsplit]])

Return a list of the words in the string, using sep as the delimiter 
string. ... Splitting an empty string with a specified separator returns 
"['']".

If sep is not specified or is None, a different splitting algorithm is 
applied. ... Splitting an empty string or a string consisting of just 
whitespace returns an empty list.


Note the bit in the second paragraph.

Here's my code snippet:

Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit 
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
--> test = ''
--> test.split()
[]
--> test.split(' ')
['']
--> test.split(',')
['']
--> test.split(None)
[]

Hope this helps!

~Ethan~



More information about the Python-list mailing list