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

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

    If str.title() doesn't work for you, do the capitalization yourself.

    1. Split the string into a list of words
    2. Capitalize the first letter of each word
    3. Join the words into a single string

    One-liner:

    >>> ' '.join([s[0].upper() + s[1:] for s in "they're bill's friends from the UK".split(' ')])
    "They're Bill's Friends From The UK"
    

    Clear example:

    input = "they're bill's friends from the UK"
    words = input.split(' ')
    capitalized_words = []
    for word in words:
        title_case_word = word[0].upper() + word[1:]
        capitalized_words.append(title_case_word)
    output = ' '.join(capitalized_words)
    

提交回复
热议问题