'How can I split a string based on the title of the words? [duplicate]
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 1:[1]
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']
Solution 2:[2]
Can't do it with the split method, but doable with re:
import re
namesL = re.split("(?=[A-Z])", names)[1:]
Keep in mind the first entry will be an empty string (as the first word is also capitalized) so we're removing it.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jonatrios |
| Solution 2 | Bharel |
