How can I capitalize the first letter of each word in a string?

前端 未结 19 2281
深忆病人
深忆病人 2020-11-22 17:17
s = \'the brown fox\'

...do something here...

s should be:

\'The Brown Fox\'

What\'s the easiest

19条回答
  •  情深已故
    2020-11-22 17:35

    Although all the answers are already satisfactory, I'll try to cover the two extra cases along with the all the previous case.

    if the spaces are not uniform and you want to maintain the same

    string = hello    world i  am    here.
    

    if all the string are not starting from alphabets

    string = 1 w 2 r 3g
    

    Here you can use this:

    def solve(s):
        a = s.split(' ')
        for i in range(len(a)):
            a[i]= a[i].capitalize()
        return ' '.join(a)
    

    This will give you:

    output = Hello    World I  Am    Here
    output = 1 W 2 R 3g
    

提交回复
热议问题