Skip to content
Advertisement

How to do CamelCase split in python

What I was trying to achieve, was something like this:

JavaScript

So I searched and found this perfect regular expression:

JavaScript

As the next logical step I tried:

JavaScript

Why does this not work, and how do I achieve the result from the linked question in python?

Edit: Solution summary

I tested all provided solutions with a few test cases:

JavaScript

In summary you could say the solution by @kalefranz does not match the question (see the last case) and the solution by @casimir et hippolyte eats a single space, and thereby violates the idea that a split should not change the individual parts. The only difference among the remaining two alternatives is that my solution returns a list with the empty string on an empty string input and the solution by @200_success returns an empty list. I don’t know how the python community stands on that issue, so I say: I am fine with either one. And since 200_success’s solution is simpler, I accepted it as the correct answer.

Advertisement

Answer

As @AplusKminus has explained, re.split() never splits on an empty pattern match. Therefore, instead of splitting, you should try finding the components you are interested in.

Here is a solution using re.finditer() that emulates splitting:

JavaScript
Advertisement