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

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

    Don't overlook the preservation of white space. If you want to process 'fred flinstone' and you get 'Fred Flinstone' instead of 'Fred Flinstone', you've corrupted your white space. Some of the above solutions will lose white space. Here's a solution that's good for Python 2 and 3 and preserves white space.

    def propercase(s):
        return ''.join(map(''.capitalize, re.split(r'(\s+)', s)))
    

提交回复
热议问题