Search code examples
pythoncpu-wordseparator

word separator for python coding


So the question reads:

Write a program that accepts as input a sentence in which all of the words are run together but the first character of each word is uppercase. Convert the sentence to a string in which the words are separated by spaces and only the first word starts with an uppercase letter. For example the string "StopAndSmellTheRoses." would be converted to " Stop and smell the roses."

I am so confused this my code so far.

def main():

    #User enters a sentence
    my_string=input('enter a sentence: ')
    print(my_string.capitalize())

main()

Solution

  • 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.