Home > Net >  Separating a string with large letters into words that begin with the same letters
Separating a string with large letters into words that begin with the same letters

Time:02-11

Suppose you have a string "TodayIsABeautifulDay". How can we get separate it in Python into words like this ["Today", "Is", "A", "Beautiful", "Day"]?

CodePudding user response:

First, use an empty list ‘words’ and append the first letter of ‘word’ to it. Now using a for loop, check if the current character is in lower case or not, if yes append it to the current string, otherwise, if uppercase, begin a new individual string.

def split_words(word):
words = [[word[0]]]

for char in word[1:]:
    if words[-1][-1].islower() and char.isupper():
        words.append(list(char))
    else:
        words[-1].append(char)

return [''.join(word) for word in words]

You can use this function :

word = "TodayIsABeautifulDay"
print(split_words(word))
  • Related