Skip to main content

Python: How to Split String with Empty Separator

Greetings.

First of all, this is in Python 2.7x.


For instance, we have this string:

If we use split with an empty string "" or '', it will return error.

ValueError


In JavaScript, we can directly use empty separator. Like so:

That cannot be done in Python. Below is some of the methods in Python.


Use list() Function

➡️ list() documentation


Use map() Function

➡️ map() documentation


Generic Method

String is an iterable object, so we can directly use the index of each string and / or do iteration using for.

Let's initiate a list object, get each string value using for, and copy it to the newly created object:

The snippet above means:

Initiate a list object, get each string value using for, and copy it to the newly created object.

Cheers!

Monkey Raptor uses cookies for analytics, advertisements, and functionality. Privacy Policy