문제

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()
도움이 되었습니까?

해결책

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.

다른 팁

Welcome to SO!

One way to do this is to loop through your string, checking the chars one by one:

#You've learned how to iterate through something, right?
i = 0 #a counter
for c in my_string: #get the characters of my_string, one by one.
    if c.isupper():        #check if it's in upper case
        if i == 0: #if it's the first letter
            new_string += c   #let it be like the original
        else:
            new_string += ' '+.lower() #it's not the first letter, 
            #so add space, and lower the letter.
else:
    new_string += c    #else, only add the letter to the new string
i += 1

Edit added a double-check to see if it's the first letter of the sentence or not. Updated demo.

As an alternative to using a counter, you can also use the built-in function enumerate, which returns a tuple of index and values.

for i,c in enumerate(my_string): #get the characters of my_string, one by one.
    if c.isupper():        #check if it's in upper case
        if i == 0: #if it's the first letter
            new_string += c   #let it be like the original
        else:
            new_string += ' '+c.lower() #it's not the first letter, 
            #so add space, and lower the letter.
else:
    new_string += c    #else, only add the letter to the new string

Demo

>>> my_string = 'ImCool'
>>> new_string = ''
>>> i = 0 #a counter
>>> for c in my_string: #get the characters of my_string, one by one.
    if c.isupper():        #check if it's in upper case
        if i == 0: #if it's the first letter
            new_string += c   #let it be like the original
        else:
            new_string += ' '+.lower() #it's not the first letter, 
            #so add space, and lower the letter.
else:
    new_string += c    #else, only add the letter to the new string
    i += 1


>>> new_string
'Im cool'

Hope this helps!

You'll need a bit of regex.

import re
split = re.findall(r'[A-Z][a-z\.]+', 'HelloThisIsMyString.')

You'll also need to join those together (inserting spaces)

' '.join(...)

and handle case conversions

' '.join(word.lower() for word in split)

(and as you already did, capitalize the first word)

' '.join(word.lower() for word in split).capitalize()

It appears that you are a little confused and this is to be expected if you are new to Python. I'm assuming you take input from the user as opposed to input for a function. Either way I would create a simple function that you could insert the users input into. The function below will accomplish what the problem asks.

def sentenceSplitter(sentence):
result = ""
for i, x in enumerate(sentence):  #i is character index, x is the element
    if i == 0:
        result = result + x
    elif x.isupper() == False:  #if element is not uppercase, add it to the result
        result = result + x
    else:                       # Otherwise, add a space and lowercase the next letter
        result = result + " " +x.lower()
return(result)

To reiterate, if you are looking to print out the sentence you would write this after the function:

def main():

#User enters a sentence
my_string=input('enter a sentence: ')
print(sentenceSplitter(my_string))
main()

If you are still confused feel free to ask any further questions.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top