You can loop through the string and add a character each time to a result:
my_string = "StopAndSmellTheRoses"
i = 0
result = ""
for c in my_string:
if c.isupper() and i > 0:
result += " "
result += c.lower()
else:
result += c
i += 1
print result
We'll use c
for each character as we walk through the string and we'll use i
to keep track of the position in the string.
There are two possibilities: it's either an uppercase character (excluding the first one) or it's not.
- In the first case we'll add a space and that character as lowercase to the result. This ensures a space is inserted before each uppercase character further in the sentence.
- In the second case it's a lowercase character or the uppercase character at the beginning of the sentence. We don't have to do anything with these and we'll add it right away.
Lastly we add one to i
whenever we're done with a character (i += 1
) as this means we correctly know where we are in the sentence.