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

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

    Capitalize string with non-uniform spaces

    I would like to add to @Amit Gupta's point of non-uniform spaces:

    From the original question, we would like to capitalize every word in the string s = 'the brown fox'. What if the string was s = 'the brown fox' with non-uniform spaces.

    def solve(s):
        # If you want to maintain the spaces in the string, s = 'the brown      fox'
        # Use s.split(' ') instead of s.split().
        # s.split() returns ['the', 'brown', 'fox']
        # while s.split(' ') returns ['the', 'brown', '', '', '', '', '', 'fox']
        capitalized_word_list = [word.capitalize() for word in s.split(' ')]
        return ' '.join(capitalized_word_list)
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 17:24

    Copy-paste-ready version of @jibberia anwser:

    def capitalize(line):
        return ' '.join(s[:1].upper() + s[1:] for s in line.split(' '))
    
    0 讨论(0)
  • 2020-11-22 17:24

    As Mark pointed out, you should use .title():

    "MyAwesomeString".title()
    

    However, if would like to make the first letter uppercase inside a Django template, you could use this:

    {{ "MyAwesomeString"|title }}
    

    Or using a variable:

    {{ myvar|title }}
    
    0 讨论(0)
  • 2020-11-22 17:24

    Easiest solution for your question, it worked in my case:

    import string
    def solve(s):
        return string.capwords(s,' ') 
        
    s=input()
    res=solve(s)
    print(res)
    
    0 讨论(0)
  • 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))
    
    0 讨论(0)
提交回复
热议问题