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

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

    Capitalize string with non-uniform spaces

    I would like to add to @Amit Gupta's point of non-uniform spaces:

    From the original question, we would like to capitalize every word in the string s = 'the brown fox'. What if the string was s = 'the brown fox' with non-uniform spaces.

    def solve(s):
        # If you want to maintain the spaces in the string, s = 'the brown      fox'
        # Use s.split(' ') instead of s.split().
        # s.split() returns ['the', 'brown', 'fox']
        # while s.split(' ') returns ['the', 'brown', '', '', '', '', '', 'fox']
        capitalized_word_list = [word.capitalize() for word in s.split(' ')]
        return ' '.join(capitalized_word_list)
    

提交回复
热议问题