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

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

    I really like this answer:

    Copy-paste-ready version of @jibberia anwser:

    def capitalize(line):
        return ' '.join([s[0].upper() + s[1:] for s in line.split(' ')])
    

    But some of the lines that I was sending split off some blank '' characters that caused errors when trying to do s[1:]. There is probably a better way to do this, but I had to add in a if len(s)>0, as in

    return ' '.join([s[0].upper() + s[1:] for s in line.split(' ') if len(s)>0])
    
    0 讨论(0)
提交回复
热议问题