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

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

    Here's a summary of different ways to do it, they will work for all these inputs:

    ""           => ""       
    "a b c"      => "A B C"             
    "foO baR"    => "FoO BaR"      
    "foo    bar" => "Foo    Bar"   
    "foo's bar"  => "Foo's Bar"    
    "foo's1bar"  => "Foo's1bar"    
    "foo 1bar"   => "Foo 1bar"     
    

    - The simplest solution is to split the sentence into words and capitalize the first letter then join it back together:

    # Be careful with multiple spaces, and empty strings
    # for empty words w[0] would cause an index error, 
    # but with w[:1] we get an empty string as desired
    def cap_sentence(s):
      return ' '.join(w[:1].upper() + w[1:] for w in s.split(' ')) 
    

    - If you don't want to split the input string into words first, and using fancy generators:

    # Iterate through each of the characters in the string and capitalize 
    # the first char and any char after a blank space
    from itertools import chain 
    def cap_sentence(s):
      return ''.join( (c.upper() if prev == ' ' else c) for c, prev in zip(s, chain(' ', s)) )
    

    - Or without importing itertools:

    def cap_sentence(s):
      return ''.join( (c.upper() if i == 0 or s[i-1] == ' ' else c) for i, c in enumerate(s) )
    

    - Or you can use regular expressions, from steveha's answer:

    # match the beginning of the string or a space, followed by a non-space
    import re
    def cap_sentence(s):
      return re.sub("(^|\s)(\S)", lambda m: m.group(1) + m.group(2).upper(), s)
    

    Now, these are some other answers that were posted, and inputs for which they don't work as expected if we are using the definition of a word being the start of the sentence or anything after a blank space:

      return s.title()
    
    # Undesired outputs: 
    "foO baR"    => "Foo Bar"       
    "foo's bar"  => "Foo'S Bar" 
    "foo's1bar"  => "Foo'S1Bar"     
    "foo 1bar"   => "Foo 1Bar"      
    

      return ' '.join(w.capitalize() for w in s.split())    
      # or
      import string
      return string.capwords(s)
    
    # Undesired outputs:
    "foO baR"    => "Foo Bar"      
    "foo    bar" => "Foo Bar"      
    

    using ' ' for the split will fix the second output, but capwords() still won't work for the first

      return ' '.join(w.capitalize() for w in s.split(' '))    
      # or
      import string
      return string.capwords(s, ' ')
    
    # Undesired outputs:
    "foO baR"    => "Foo Bar"      
    

    Be careful with multiple blank spaces

      return ' '.join(w[0].upper() + w[1:] for w in s.split())
    # Undesired outputs:
    "foo    bar" => "Foo Bar"                 
    

提交回复
热议问题