Complications in for loop for Capitalizing words in a string in Python 3

112 Views Asked by At

I'm Trying to capitalize the words in a string using this technique:

 def solve(s):
     if len(s)>0 and len(s)<1000:
         li= s.split(" ")

         for i in li:
             i= i.capitalize()

     return " ".join(li)

But this just doesn't seem to work. On the other hand while I'm using the below technique, it works perfectly fine. Please help me with the use of two kinds "for" loop in two cases.

def solve(s):
    if len(s)>0 and len(s)<1000:
        li= s.split(" ")

        for i in range(len(li)):
            li[i]= li[i].capitalize()

    return " ".join(li)
2

There are 2 best solutions below

0
On BEST ANSWER

In the above line you are not throwing the capitalized value to the li variable, youare just replacing the value of the actual element:

 for i in li:
     i= i.capitalize()

In your second approach you are throwing the value to li variable again, that's why it works on the second case.

0
On

You do realize strings have a builtin method to do exactly that?

>>> "hello world this is a test".title()
'Hello World This Is A Test'
>>>