Search code examples
pythonbuilt-in

How can I split a string based on the title of the words?


For example I have followed string:

names = "JohnDoeEmmyGooseRichardNickson"

How can I split that string based on the title of the words? So every time a capital letter occurs, the string will be split up.

Is there a way to do this with the split() method? (no regex)

That I will get:

namesL = ["John","Doe","Emmy","Goose","Richard","Nickson"]

Solution

  • You can do it with regex

    >>> import re
    >>> s = "TheLongAndWindingRoad ABC A123B45"
    >>> re.sub( r"([A-Z])", r" \1", s).split()
    # output
    ['The', 'Long', 'And', 'Winding', 'Road', 'A', 'B', 'C', 'A123', 'B45']