How to capitalize the first letter of each word in

2019-01-01 03:18发布

s = 'the brown fox'

...do something here...

s should be :

'The Brown Fox'

What's the easiest way to do this?

15条回答
春风洒进眼中
2楼-- · 2019-01-01 03:37

Here's a summary of different ways to do it:

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)

These 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"     

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"                 
查看更多
与君花间醉酒
3楼-- · 2019-01-01 03:42

An empty string will raise an Error if you access [1:], therefore I would use:

def my_uppercase(title):
    if not title:
       return ''
    return title[0].upper() + title[1:]

to uppercase the first letter only.

查看更多
刘海飞了
4楼-- · 2019-01-01 03:43

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 }}
查看更多
登录 后发表回答