str.split() with empty separator

MRAB python at mrabarnett.plus.com
Tue Sep 15 12:30:30 EDT 2009


Vlastimil Brom wrote:
> 2009/9/15 Ulrich Eckhardt <eckhardt at satorlaser.com>:
>> Hi!
>>
>> "'abc'.split('')" gives me a "ValueError: empty separator".
>> However, "''.join(['a', 'b', 'c'])" gives me "'abc'".
>>
>> Why this asymmetry? I was under the impression that the two would be
>> complementary.
>>
>> Uli
>>
> 
> maybe it isn't quite obvious, what the behaviour in this case should be;
> re.split also works with empty delimiter (and returns the original string)
>>>> re.split("", "abcde")
> ['abcde']
> 
> If you need to split the string into the list of single characters
> like in your example, list() is the possible way:
>>>> list("abcde")
> ['a', 'b', 'c', 'd', 'e']
> 
I'd prefer it to split into characters. As for re.split, there are times
when it would be nice to be able to split on a zero-width match such as
r"\b" (word boundary).



More information about the Python-list mailing list