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

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

    The .title() method can't work well,

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

    Try string.capwords() method,

    import string
    string.capwords("they're bill's friends from the UK")
    >>>"They're Bill's Friends From The Uk"
    

    From the Python documentation on capwords:

    Split the argument into words using str.split(), capitalize each word using str.capitalize(), and join the capitalized words using str.join(). If the optional second argument sep is absent or None, runs of whitespace characters are replaced by a single space and leading and trailing whitespace are removed, otherwise sep is used to split and join the words.

提交回复
热议问题