A pythonic way to insert a space before capital letters A pythonic way to insert a space before capital letters python python

A pythonic way to insert a space before capital letters


You could try:

>>> re.sub(r"(\w)([A-Z])", r"\1 \2", "WordWordWord")'Word Word Word'


If there are consecutive capitals, then Gregs result couldnot be what you look for, since the \w consumes the caracterin front of the captial letter to be replaced.

>>> re.sub(r"(\w)([A-Z])", r"\1 \2", "WordWordWWWWWWWord")'Word Word WW WW WW Word'

A look-behind would solve this:

>>> re.sub(r"(?<=\w)([A-Z])", r" \1", "WordWordWWWWWWWord")'Word Word W W W W W W Word'


Have a look at my answer on .NET - How can you split a “caps” delimited string into an array?

Edit: Maybe better to include it here.

re.sub(r'([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))', r'\1 ', text)

For example:

"SimpleHTTPServer" => ["Simple", "HTTP", "Server"]