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

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

    Why do you complicate your life with joins and for loops when the solution is simple and safe??

    Just do this:

    string = "the brown fox"
    string[0].upper()+string[1:]
    
    0 讨论(0)
  • 2020-11-22 17:37

    A quick function worked for Python 3

    Python 3.6.9 (default, Nov  7 2019, 10:44:02) 
    [GCC 8.3.0] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> capitalizeFirtChar = lambda s: s[:1].upper() + s[1:]
    >>> print(capitalizeFirtChar('помните своих Предковъ. Сражайся за Правду и Справедливость!'))
    Помните своих Предковъ. Сражайся за Правду и Справедливость!
    >>> print(capitalizeFirtChar('хай живе вільна Україна! Хай живе Любовь поміж нас.'))
    Хай живе вільна Україна! Хай живе Любовь поміж нас.
    >>> print(capitalizeFirtChar('faith and Labour make Dreams come true.'))
    Faith and Labour make Dreams come true.
    
    0 讨论(0)
  • 2020-11-22 17:38

    In case you want to downsize

    # Assuming you are opening a new file
    with open(input_file) as file:
        lines = [x for x in reader(file) if x]
    
    # for loop to parse the file by line
    for line in lines:
        name = [x.strip().lower() for x in line if x]
        print(name) # Check the result
    
    0 讨论(0)
  • 2020-11-22 17:42

    Don't overlook the preservation of white space. If you want to process 'fred flinstone' and you get 'Fred Flinstone' instead of 'Fred Flinstone', you've corrupted your white space. Some of the above solutions will lose white space. Here's a solution that's good for Python 2 and 3 and preserves white space.

    def propercase(s):
        return ''.join(map(''.capitalize, re.split(r'(\s+)', s)))
    
    0 讨论(0)
  • 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"                 
    
    0 讨论(0)
  • 2020-11-22 17:45

    If only you want the first letter:

    >>> 'hello world'.capitalize()
    'Hello world'
    

    But to capitalize each word:

    >>> 'hello world'.title()
    'Hello World'
    
    0 讨论(0)
提交回复
热议问题