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

前端 未结 19 2278
深忆病人
深忆病人 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:28

    The suggested method str.title() does not work in all cases. For example:

    string = "a b 3c"
    string.title()
    > "A B 3C"
    

    instead of "A B 3c".

    I think, it is better to do something like this:

    def capitalize_words(string):
        words = string.split(" ") # just change the split(" ") method
        return ' '.join([word.capitalize() for word in words])
    
    capitalize_words(string)
    >'A B 3c'
    

提交回复
热议问题