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

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

    To capitalize words...

    str = "this is string example....  wow!!!";
    print "str.title() : ", str.title();
    

    @Gary02127 comment, the below solution works with title with apostrophe

    import re
    
    def titlecase(s):
        return re.sub(r"[A-Za-z]+('[A-Za-z]+)?", lambda mo: mo.group(0)[0].upper() + mo.group(0)[1:].lower(), s)
    
    text = "He's an engineer, isn't he? SnippetBucket.com "
    print(titlecase(text))
    

提交回复
热议问题