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

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

    The .title() method of a string (either ASCII or Unicode is fine) does this:

    >>> "hello world".title()
    'Hello World'
    >>> u"hello world".title()
    u'Hello World'
    

    However, look out for strings with embedded apostrophes, as noted in the docs.

    The algorithm uses a simple language-independent definition of a word as groups of consecutive letters. The definition works in many contexts but it means that apostrophes in contractions and possessives form word boundaries, which may not be the desired result:

    >>> "they're bill's friends from the UK".title()
    "They'Re Bill'S Friends From The Uk"
    

提交回复
热议问题