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) )
# 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:
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.
If you don't want to split the input string into words first, and using fancy generators:
or without importing itertools
or you can use regular expressions, from steveha's answer
These will work for all these inputs:
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:
using ' ' for the split will fix the second output, but capwords() still won't work for the first
Be careful with multiple blank spaces
An empty string will raise an Error if you access [1:], therefore I would use:
to uppercase the first letter only.
As Mark pointed out you should use
.title()
:However, if would like to make the first letter uppercase inside a django template, you could use this:
or using a variable: