-1

sorry if this is a duplicate, but I haven't found any clear answer out there.

Basically, my program should capitalize a string like this :

'some words'

Into something like this :

'Some Words'

Here is my code:

mystring = "some words"
copy_of_mystring = ""
word = ""

for i in mystring:
    if i==" ":
        for j in range(1):

            #capitalize if my word has more than 1 letter
            if len(word) > 1:
                word=str.upper(word[0]) + word[1:]

            #capitalize if word has only 1 letter
            elif len(word)==1:
                word=str.upper(word[0])

            copy_of_mystring += word + " "
        word = ""
    else:
        word += i
print(copy_of_mystring)

So basically my first loop add i to word until i is a space.

Then my second loop will start and capitalize word and add it to copy_of_mystring, that part is working.

And this is when my problem comes in. When my first loop is "building" my last word, it will of course won't find any space after it, so my problem comes from this condition :

if i==" ":

I tried this :

if i==" " or i==mystring[-1]:

But, in a string where several characters is the same as the last one, like in 'morgana', for example, it would end up like this

'Morg N'

So, is there a way to check if my character i is the VERY LAST one in mystring ?

P.S: Sorry if this sounds like a really basic mistake but I'm still learning all the things we can do with strings.

Tiphe
  • 3
  • 3
  • I think my_string.title() is enough for that... – Walter_Ritzel Mar 15 '16 at 23:31
  • You could also split the string on the space into an array, capitalize the first digit of each string in the array, and then rejoin the elements of the array by a space (reform the array into one string). – the happy mamba Mar 15 '16 at 23:32
  • When you exit out of the loop, `word` will contain the last processed word. Just capitalize it. – Dmitry B. Mar 15 '16 at 23:33
  • I don't understand why you are asking about checking the last of anything. You only care about the first letters of the words – OneCricketeer Mar 15 '16 at 23:35
  • Because I capitalize `word` only if the next character is a space, but that won't work for the last one since there is no space after it. – Tiphe Mar 15 '16 at 23:39

1 Answers1

1

Python strings already support this via the title() method.

>>> 'some words'.title()
'Some Words'
Brendan Abel
  • 35,343
  • 14
  • 88
  • 118